From 3859418e904b7526b524603aeeaf4b53d94c5083 Mon Sep 17 00:00:00 2001 From: YX Hao Date: Tue, 21 Jun 2022 13:08:03 +0800 Subject: [PATCH] Indent to spaces for %i in (*.c *.h) do expand --tabs=4 %i >..\new\%i --- addresslist.c | 350 +++++----- addresslist.h | 38 +- array.c | 212 +++--- array.h | 78 +-- bst.c | 20 +- bst.h | 26 +- cacheht.c | 406 +++++------ cacheht.h | 44 +- cachettlcrtl.c | 138 ++-- cachettlcrtl.h | 22 +- common.h | 436 ++++++------ dnscache.c | 824 +++++++++++----------- dnsgenerator.c | 108 +-- dnsgenerator.h | 18 +- dnsparser.c | 264 ++++---- dnsparser.h | 144 ++-- dnsrelated.c | 160 ++--- dnsrelated.h | 100 +-- domainstatistic.c | 390 +++++------ domainstatistic.h | 12 +- downloader.c | 530 +++++++-------- downloader.h | 30 +- dynamichosts.c | 174 ++--- filter.c | 138 ++-- goodiplist.c | 160 ++--- hcontext.c | 18 +- hosts.c | 50 +- hostscontainer.c | 302 ++++----- hostscontainer.h | 20 +- hostsutils.c | 20 +- iheader.h | 20 +- ipchunk.c | 156 ++--- ipchunk.h | 18 +- ipmisc.c | 4 +- linkedqueue.h | 2 +- logs.c | 102 +-- logs.h | 12 +- main.c | 280 ++++---- mcontext.c | 14 +- mcontext.h | 2 +- mmgr.c | 2 +- querydnslistentcp.c | 634 ++++++++--------- readconfig.c | 592 ++++++++-------- readconfig.h | 74 +- readline.c | 186 ++--- readline.h | 6 +- rwlock.h | 102 +-- simpleht.c | 234 +++---- simpleht.h | 14 +- socketpool.c | 16 +- socketpool.h | 6 +- statichosts.c | 42 +- stringchunk.c | 434 ++++++------ stringlist.c | 26 +- tcpm.c | 202 +++--- udpm.c | 10 +- utils.c | 1580 +++++++++++++++++++++---------------------- utils.h | 16 +- 58 files changed, 5009 insertions(+), 5009 deletions(-) diff --git a/addresslist.c b/addresslist.c index 294bb3bc..833349e7 100755 --- a/addresslist.c +++ b/addresslist.c @@ -7,225 +7,225 @@ int AddressList_Init(AddressList *a) { - if( a == NULL ) - { - return 0; - } - - if( Array_Init(&(a->AddressList), sizeof(Address_Type), 8, FALSE, NULL) != 0 ) - { - return -1; - } - - a->Counter = 0; - return 0; + if( a == NULL ) + { + return 0; + } + + if( Array_Init(&(a->AddressList), sizeof(Address_Type), 8, FALSE, NULL) != 0 ) + { + return -1; + } + + a->Counter = 0; + return 0; } -int AddressList_Add(AddressList *a, Address_Type *Addr) +int AddressList_Add(AddressList *a, Address_Type *Addr) { - if( a == NULL ) - { - return -1; - } - - if( Array_PushBack(&(a->AddressList), Addr, NULL) < 0 ) - { - return -1; - } else { - return 0; - } + if( a == NULL ) + { + return -1; + } + + if( Array_PushBack(&(a->AddressList), Addr, NULL) < 0 ) + { + return -1; + } else { + return 0; + } } sa_family_t AddressList_ConvertFromString(Address_Type *Out, const char *Addr_Port, int DefaultPort) { - sa_family_t Family; - - memset(Out, 0, sizeof(Address_Type)); - - Family = GetAddressFamily(Addr_Port); - Out->family = Family; - - switch( Family ) - { - case AF_INET6: - { - char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0}; - in_port_t Port; - const char *PortPos; - - memset(Addr, 0, sizeof(Addr)); - - PortPos = strchr(Addr_Port, ']'); - if( PortPos == NULL ) - { - return AF_UNSPEC; - } - - PortPos = strchr(PortPos, ':'); - if( PortPos == NULL ) - { - sscanf(Addr_Port + 1, "%[^]]", Addr); - Port = DefaultPort; - } else { - int Port_warpper; - - sscanf(Addr_Port + 1, "%[^]]", Addr); - sscanf(PortPos + 1, "%d", &Port_warpper); - Port = Port_warpper; - } - - Out->Addr.Addr6.sin6_family = Family; - Out->Addr.Addr6.sin6_port = htons(Port); - - IPv6AddressToNum(Addr, &(Out->Addr.Addr6.sin6_addr)); - - return AF_INET6; - } - break; - - case AF_INET: - { - char Addr[] = "xxx.xxx.xxx.xxx"; - in_port_t Port; - const char *PortPos; - - memset(Addr, 0, sizeof(Addr)); - - PortPos = strchr(Addr_Port, ':'); - if( PortPos == NULL ) - { - sscanf(Addr_Port, "%s", Addr); - Port = DefaultPort; - } else { - int Port_warpper; - sscanf(Addr_Port, "%[^:]", Addr); - sscanf(PortPos + 1, "%d", &Port_warpper); - Port = Port_warpper; - } - FILL_ADDR4(Out->Addr.Addr4, Family, Addr, Port); - - return AF_INET; - } - break; - - default: - return AF_UNSPEC; - break; - } + sa_family_t Family; + + memset(Out, 0, sizeof(Address_Type)); + + Family = GetAddressFamily(Addr_Port); + Out->family = Family; + + switch( Family ) + { + case AF_INET6: + { + char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0}; + in_port_t Port; + const char *PortPos; + + memset(Addr, 0, sizeof(Addr)); + + PortPos = strchr(Addr_Port, ']'); + if( PortPos == NULL ) + { + return AF_UNSPEC; + } + + PortPos = strchr(PortPos, ':'); + if( PortPos == NULL ) + { + sscanf(Addr_Port + 1, "%[^]]", Addr); + Port = DefaultPort; + } else { + int Port_warpper; + + sscanf(Addr_Port + 1, "%[^]]", Addr); + sscanf(PortPos + 1, "%d", &Port_warpper); + Port = Port_warpper; + } + + Out->Addr.Addr6.sin6_family = Family; + Out->Addr.Addr6.sin6_port = htons(Port); + + IPv6AddressToNum(Addr, &(Out->Addr.Addr6.sin6_addr)); + + return AF_INET6; + } + break; + + case AF_INET: + { + char Addr[] = "xxx.xxx.xxx.xxx"; + in_port_t Port; + const char *PortPos; + + memset(Addr, 0, sizeof(Addr)); + + PortPos = strchr(Addr_Port, ':'); + if( PortPos == NULL ) + { + sscanf(Addr_Port, "%s", Addr); + Port = DefaultPort; + } else { + int Port_warpper; + sscanf(Addr_Port, "%[^:]", Addr); + sscanf(PortPos + 1, "%d", &Port_warpper); + Port = Port_warpper; + } + FILL_ADDR4(Out->Addr.Addr4, Family, Addr, Port); + + return AF_INET; + } + break; + + default: + return AF_UNSPEC; + break; + } } int AddressList_Add_From_String(AddressList *a, const char *Addr_Port, int DefaultPort) { - Address_Type Tmp; + Address_Type Tmp; - if( AddressList_ConvertFromString(&Tmp, Addr_Port, DefaultPort) == AF_UNSPEC ) - { - return -1; - } + if( AddressList_ConvertFromString(&Tmp, Addr_Port, DefaultPort) == AF_UNSPEC ) + { + return -1; + } - return AddressList_Add(a, &Tmp); + return AddressList_Add(a, &Tmp); } int AddressList_Advance(AddressList *a) { - if( a == NULL ) - { - return 0; - } + if( a == NULL ) + { + return 0; + } - return (a->Counter)++; + return (a->Counter)++; } struct sockaddr *AddressList_GetOneBySubscript(AddressList *a, sa_family_t *family, int Subscript) { - Address_Type *Result; - - if( a == NULL ) - { - return 0; - } - - Result = (Address_Type *)Array_GetBySubscript(&(a->AddressList), Subscript); - if( Result == NULL ) - { - return NULL; - } else { - if( family != NULL ) - { - *family = Result->family; - } - return (struct sockaddr *)&(Result->Addr); - } + Address_Type *Result; + + if( a == NULL ) + { + return 0; + } + + Result = (Address_Type *)Array_GetBySubscript(&(a->AddressList), Subscript); + if( Result == NULL ) + { + return NULL; + } else { + if( family != NULL ) + { + *family = Result->family; + } + return (struct sockaddr *)&(Result->Addr); + } } struct sockaddr *AddressList_GetOne(AddressList *a, sa_family_t *family) { - return AddressList_GetOneBySubscript(a, family, a->Counter % Array_GetUsed(&(a->AddressList))); + return AddressList_GetOneBySubscript(a, family, a->Counter % Array_GetUsed(&(a->AddressList))); } struct sockaddr **AddressList_GetPtrListOfFamily(AddressList *a, sa_family_t family) { - int Itr; - int NumberOfAddresses = AddressList_GetNumberOfAddresses(a); - struct sockaddr **AddrList, **AddrList_Ori; - struct sockaddr *OneAddr; - sa_family_t OneFamily = AF_UNSPEC; - - AddrList = SafeMalloc(sizeof(struct sockaddr *) * (NumberOfAddresses + 1)); - if( AddrList == NULL ) - { - return NULL; - } - - AddrList_Ori = AddrList; - Itr = 0; - while( Itr != NumberOfAddresses ) - { - OneAddr = AddressList_GetOneBySubscript(a, &OneFamily, Itr); - if( OneFamily == family ) - { - *AddrList = OneAddr; - ++AddrList; - } - ++Itr; - } - - *AddrList = NULL; - return AddrList_Ori; + int Itr; + int NumberOfAddresses = AddressList_GetNumberOfAddresses(a); + struct sockaddr **AddrList, **AddrList_Ori; + struct sockaddr *OneAddr; + sa_family_t OneFamily = AF_UNSPEC; + + AddrList = SafeMalloc(sizeof(struct sockaddr *) * (NumberOfAddresses + 1)); + if( AddrList == NULL ) + { + return NULL; + } + + AddrList_Ori = AddrList; + Itr = 0; + while( Itr != NumberOfAddresses ) + { + OneAddr = AddressList_GetOneBySubscript(a, &OneFamily, Itr); + if( OneFamily == family ) + { + *AddrList = OneAddr; + ++AddrList; + } + ++Itr; + } + + *AddrList = NULL; + return AddrList_Ori; } struct sockaddr **AddressList_GetPtrList(AddressList *a, sa_family_t **families) { - int Itr; + int Itr; - int NumberOfAddresses = AddressList_GetNumberOfAddresses(a); - struct sockaddr **AddrList; + int NumberOfAddresses = AddressList_GetNumberOfAddresses(a); + struct sockaddr **AddrList; - AddrList = SafeMalloc(sizeof(struct sockaddr *) * (NumberOfAddresses + 1)); - if( AddrList == NULL ) - { - return NULL; - } + AddrList = SafeMalloc(sizeof(struct sockaddr *) * (NumberOfAddresses + 1)); + if( AddrList == NULL ) + { + return NULL; + } - *families = SafeMalloc(sizeof(sa_family_t) * (NumberOfAddresses + 1)); + *families = SafeMalloc(sizeof(sa_family_t) * (NumberOfAddresses + 1)); if( *families == NULL ) { - SafeFree(AddrList); - return NULL; + SafeFree(AddrList); + return NULL; } - Itr = 0; - while( Itr != NumberOfAddresses ) - { - AddrList[Itr] = AddressList_GetOneBySubscript(a, &((*families)[Itr]), Itr); + Itr = 0; + while( Itr != NumberOfAddresses ) + { + AddrList[Itr] = AddressList_GetOneBySubscript(a, &((*families)[Itr]), Itr); - ++Itr; - } + ++Itr; + } - AddrList[Itr] = NULL; - (*families)[Itr] = AF_UNSPEC; - return AddrList; + AddrList[Itr] = NULL; + (*families)[Itr] = AF_UNSPEC; + return AddrList; } diff --git a/addresslist.h b/addresslist.h index ada63e9d..06564f15 100755 --- a/addresslist.h +++ b/addresslist.h @@ -10,13 +10,13 @@ typedef struct _AddressList { - /* An array of `Address_Type' */ - Array AddressList; + /* An array of `Address_Type' */ + Array AddressList; - /* The `Counter' is used by `AddressList_Advance' and `AddressList_GetOne', - * see them. - */ - uint32_t Counter; + /* The `Counter' is used by `AddressList_Advance' and `AddressList_GetOne', + * see them. + */ + uint32_t Counter; } AddressList; @@ -30,8 +30,8 @@ int AddressList_Init(__in AddressList *a); * 0 on success, a non-zero value otherwise. */ -int AddressList_Add(__in AddressList *a, - __in Address_Type *Addr); +int AddressList_Add(__in AddressList *a, + __in Address_Type *Addr); /* Description: * Add an address in the form of `Address_Type' to an AddressList. * Parameters: @@ -47,10 +47,10 @@ sa_family_t AddressList_ConvertFromString(__out Address_Type *Out, __in int DefaultPort ); -int AddressList_Add_From_String(__in AddressList *a, - __in const char *Addr_Port, - __in int DefaultPort - ); +int AddressList_Add_From_String(__in AddressList *a, + __in const char *Addr_Port, + __in int DefaultPort + ); /* Description: * Add an address in text to an AddressList. * Parameters: @@ -74,12 +74,12 @@ int AddressList_Advance(__in AddressList *a); * The a->Counter before it increased. */ -struct sockaddr *AddressList_GetOneBySubscript(__in AddressList *a, - __out_opt sa_family_t *family, - __in int Subscript); +struct sockaddr *AddressList_GetOneBySubscript(__in AddressList *a, + __out_opt sa_family_t *family, + __in int Subscript); -struct sockaddr *AddressList_GetOne(__in AddressList *a, - __out_opt sa_family_t *family); +struct sockaddr *AddressList_GetOne(__in AddressList *a, + __out_opt sa_family_t *family); /* Description: * Fetch an address from an AddressList. See the implementation for details. * Parameters: @@ -90,13 +90,13 @@ struct sockaddr *AddressList_GetOne(__in AddressList *a, * The pointer to the fetched address. */ -#define AddressList_GetNumberOfAddresses(a_ptr) ( Array_GetUsed(&((a_ptr)->AddressList)) ) +#define AddressList_GetNumberOfAddresses(a_ptr) ( Array_GetUsed(&((a_ptr)->AddressList)) ) /* You should free the return value and *families when they are no longer needed. */ struct sockaddr **AddressList_GetPtrListOfFamily(AddressList *a, sa_family_t family); struct sockaddr **AddressList_GetPtrList(AddressList *a, sa_family_t **families); -#define AddressList_Free(a_ptr) (Array_Free(&((a_ptr)->AddressList))) +#define AddressList_Free(a_ptr) (Array_Free(&((a_ptr)->AddressList))) /* Description: * Free an initialized AddressList. * Return value: diff --git a/array.c b/array.c index f88379d7..847654f6 100755 --- a/array.c +++ b/array.c @@ -6,48 +6,48 @@ /* if it grows down, the InitialCount will be ignored. Otherwise, TheFirstAddress will be ignored. */ int Array_Init(__in Array *a, __in int DataLength, __in int InitialCount, __in BOOL GrowsDown, __in void *TheFirstAddress /* The first means the biggest address*/) { - if( InitialCount < 0) - return 1; - - a->DataLength = DataLength; - a->Used = 0; - - if( GrowsDown == FALSE ) - { - if( InitialCount > 0 ) - { - a->Data = SafeMalloc(DataLength * InitialCount); - if( a->Data == NULL ) - return 2; - - memset(a->Data, 0, DataLength * InitialCount); - } else { - a->Data = NULL; - } - - a->Allocated = InitialCount; - } else { - a->Allocated = -1; - a->Data = TheFirstAddress; - } - - return 0; + if( InitialCount < 0) + return 1; + + a->DataLength = DataLength; + a->Used = 0; + + if( GrowsDown == FALSE ) + { + if( InitialCount > 0 ) + { + a->Data = SafeMalloc(DataLength * InitialCount); + if( a->Data == NULL ) + return 2; + + memset(a->Data, 0, DataLength * InitialCount); + } else { + a->Data = NULL; + } + + a->Allocated = InitialCount; + } else { + a->Allocated = -1; + a->Data = TheFirstAddress; + } + + return 0; } /* Subscripts are always non-negative. */ void *Array_GetBySubscript(__in const Array *a, __in int Subscript) { - if( Subscript >= 0 && Subscript < a->Used ) - { - if( a->Allocated < 0 ) - { - Subscript *= (-1); - } - - return (void *)((a->Data) + (a->DataLength) * Subscript); - } else { - return NULL; - } + if( Subscript >= 0 && Subscript < a->Used ) + { + if( a->Allocated < 0 ) + { + Subscript *= (-1); + } + + return (void *)((a->Data) + (a->DataLength) * Subscript); + } else { + return NULL; + } } void *Array_GetThis(__in Array *a, __in const void *Position) @@ -88,95 +88,95 @@ void *Array_GetNext(__in Array *a, __in const void *Position) /* Subscript returned */ int Array_PushBack(__in Array *a, __in_opt const void *Data, __in_opt void *Boundary /* Only used by grow down array */) { - if( a->Allocated >= 0 ) - { - if( a->Used == a->Allocated ) - { - int NewCount = (a->Allocated) < 2 ? 2 : (a->Allocated) + (a->Allocated) / 2; - - if( SafeRealloc((void **)&(a->Data), NewCount * (a->DataLength)) != 0 ) - { - return -1; - } - - a->Allocated = NewCount; - } - - if( Data != NULL ) - memcpy((a->Data) + (a->DataLength) * (a->Used), Data, a->DataLength); - - return (a->Used)++; - - } else { - if( Boundary != NULL && ((a->Data) + (-1) * (a->DataLength) * (a->Used)) < (char *)Boundary ) - { - return -1; - } else { - if( Data != NULL ) - { - memcpy((a->Data) + (-1) * (a->DataLength) * (a->Used), Data, a->DataLength); - } - return (a->Used)++; - } - } + if( a->Allocated >= 0 ) + { + if( a->Used == a->Allocated ) + { + int NewCount = (a->Allocated) < 2 ? 2 : (a->Allocated) + (a->Allocated) / 2; + + if( SafeRealloc((void **)&(a->Data), NewCount * (a->DataLength)) != 0 ) + { + return -1; + } + + a->Allocated = NewCount; + } + + if( Data != NULL ) + memcpy((a->Data) + (a->DataLength) * (a->Used), Data, a->DataLength); + + return (a->Used)++; + + } else { + if( Boundary != NULL && ((a->Data) + (-1) * (a->DataLength) * (a->Used)) < (char *)Boundary ) + { + return -1; + } else { + if( Data != NULL ) + { + memcpy((a->Data) + (-1) * (a->DataLength) * (a->Used), Data, a->DataLength); + } + return (a->Used)++; + } + } } void *Array_SetToSubscript(Array *a, int Subscript, const void *Data) { - if( a->Allocated >= 0 ) - { - if( Subscript >= a->Allocated ) - { - if( SafeRealloc((void **)&(a->Data), (Subscript + 1) * (a->DataLength)) != 0 ) - return NULL; + if( a->Allocated >= 0 ) + { + if( Subscript >= a->Allocated ) + { + if( SafeRealloc((void **)&(a->Data), (Subscript + 1) * (a->DataLength)) != 0 ) + return NULL; - a->Allocated = Subscript + 1; - } + a->Allocated = Subscript + 1; + } - memcpy((a->Data) + (a->DataLength) * Subscript, Data, a->DataLength); + memcpy((a->Data) + (a->DataLength) * Subscript, Data, a->DataLength); - if( a->Used < Subscript + 1 ) - a->Used = Subscript + 1; + if( a->Used < Subscript + 1 ) + a->Used = Subscript + 1; - return (a->Data) + (a->DataLength) * Subscript; - } else { - if( a->Used < Subscript + 1 ) - { - a->Used = Subscript + 1; - } + return (a->Data) + (a->DataLength) * Subscript; + } else { + if( a->Used < Subscript + 1 ) + { + a->Used = Subscript + 1; + } - memcpy((a->Data) + (-1) * (a->DataLength) * Subscript, Data, a->DataLength); + memcpy((a->Data) + (-1) * (a->DataLength) * Subscript, Data, a->DataLength); - return (a->Data) + (-1) * (a->DataLength) * Subscript; - } + return (a->Data) + (-1) * (a->DataLength) * Subscript; + } } void Array_Sort(Array *a, int (*Compare)(const void *, const void *)) { - if( a->Allocated < 0 ) - { - qsort(a->Data - (a->Used * a->DataLength), a->Used, a->DataLength, Compare); - } else { - qsort(a->Data, a->Used, a->DataLength, Compare); - } + if( a->Allocated < 0 ) + { + qsort(a->Data - (a->Used * a->DataLength), a->Used, a->DataLength, Compare); + } else { + qsort(a->Data, a->Used, a->DataLength, Compare); + } } void Array_Fill(Array *a, int Num, const void *DataSample) { - int i; - for( i = 0; i < Num; ++i ) - { - Array_SetToSubscript(a, i, DataSample); - } + int i; + for( i = 0; i < Num; ++i ) + { + Array_SetToSubscript(a, i, DataSample); + } } void Array_Free(Array *a) { - if( a->Allocated >= 0 ) - { - SafeFree(a->Data); - } - a->Data = NULL; - a->Used = 0; - a->Allocated = 0; + if( a->Allocated >= 0 ) + { + SafeFree(a->Data); + } + a->Data = NULL; + a->Used = 0; + a->Allocated = 0; } diff --git a/array.h b/array.h index d818b22c..637fa425 100755 --- a/array.h +++ b/array.h @@ -5,44 +5,44 @@ typedef struct _Array{ - /* All elements reside here */ - char *Data; - - /* Length of one element */ - int32_t DataLength; - - /* How many elements are there in this array. Always non-negative. */ - int32_t Used; - - /* How many rooms (one room one element) have been allocated. - * An Array, normally, grows up (towards high address). In this case, - * `Allocated' is non-negative. - * Typically, `Allocated' will never be less than `Used'. In most cases, - * `Allocated' is greater than `Used'. If they are equal, this means there - * is no left room for a new element, then we must allocate more - * space (realloc) just before adding new elements. The total allocated - * space is equal to `Allocated' times `DataLength'. - * - * If `Allocated' is negative, the array grows down (towarding lower address, - * like stack) and won't allocate new space. One using this should guarantee - * there is enough space to hold all elements. - */ - int32_t Allocated; + /* All elements reside here */ + char *Data; + + /* Length of one element */ + int32_t DataLength; + + /* How many elements are there in this array. Always non-negative. */ + int32_t Used; + + /* How many rooms (one room one element) have been allocated. + * An Array, normally, grows up (towards high address). In this case, + * `Allocated' is non-negative. + * Typically, `Allocated' will never be less than `Used'. In most cases, + * `Allocated' is greater than `Used'. If they are equal, this means there + * is no left room for a new element, then we must allocate more + * space (realloc) just before adding new elements. The total allocated + * space is equal to `Allocated' times `DataLength'. + * + * If `Allocated' is negative, the array grows down (towarding lower address, + * like stack) and won't allocate new space. One using this should guarantee + * there is enough space to hold all elements. + */ + int32_t Allocated; }Array; -int Array_Init( __in Array *a, - __in int DataLength, - __in int InitialCount, - __in BOOL GrowsDown, - __in void *TheFirstAddress); +int Array_Init( __in Array *a, + __in int DataLength, + __in int InitialCount, + __in BOOL GrowsDown, + __in void *TheFirstAddress); /* Description: * Initialize an Array. * Parameters: - * a : The Array to be initialized. - * DataLength : The length of one element. - * InitialCount : The number of initial allocated rooms. - * If the array grows down, this parameter will be ignored. - * GrowsDown : Whether it grows down. + * a : The Array to be initialized. + * DataLength : The length of one element. + * InitialCount : The number of initial allocated rooms. + * If the array grows down, this parameter will be ignored. + * GrowsDown : Whether it grows down. * TheFirstAddress : (Only) For growing down array, the address of the first * element (at the highist address). The address is the head * address of the element, not the tail address. @@ -51,25 +51,25 @@ int Array_Init( __in Array *a, * 0 on success, a non-zero value otherwise. */ -#define Array_Init_Static(DataLengrh) {NULL, (DataLengrh), 0, 0} +#define Array_Init_Static(DataLengrh) {NULL, (DataLengrh), 0, 0} -#define Array_IsEmpty(a_ptr) (((a_ptr)->Used) == 0) +#define Array_IsEmpty(a_ptr) (((a_ptr)->Used) == 0) /* Description: * Check if an Array is empty. * Parameters: * a_ptr : Pointer to an Array to be checked. */ -#define Array_GetUsed(a_ptr) ((a_ptr)->Used) +#define Array_GetUsed(a_ptr) ((a_ptr)->Used) /* Description: * Get `Used' of an Array. * Parameters: * a_ptr : Pointer to an Array to be gotten. */ -#define Array_GetDataLength(a_ptr) ((a_ptr)->DataLength) +#define Array_GetDataLength(a_ptr) ((a_ptr)->DataLength) -#define Array_GetRawArray(a_ptr) ((a_ptr)->Data) +#define Array_GetRawArray(a_ptr) ((a_ptr)->Data) void *Array_GetBySubscript(__in const Array *a, __in int Subscript); /* Description: @@ -125,7 +125,7 @@ void *Array_SetToSubscript(__in Array *a, __in int Subscript, __in const void *D void Array_Sort(Array *a, int (*Compare)(const void *, const void *)); -#define Array_Clear(a_ptr) ((a_ptr)->Used = 0) +#define Array_Clear(a_ptr) ((a_ptr)->Used = 0) /* Description: * Remove all elements, but their rooms are still there. * Parameters: diff --git a/bst.c b/bst.c index 62f11a0a..8f41a680 100755 --- a/bst.c +++ b/bst.c @@ -69,7 +69,7 @@ PUBFUNC const void *Bst_Add(Bst *t, const void *Data) if( t->Root == NULL ) { /* Insert as root */ - return InsertNode(t, NULL, 0, Data); + return InsertNode(t, NULL, 0, Data); } else { /* Non-root, finding the currect place to insert */ Bst_NodeHead *Current = t->Root; @@ -304,9 +304,9 @@ PUBFUNC void Bst_Delete(Bst *t, const void *Node) PUBFUNC void Bst_Reset(Bst *t) { - t->Nodes.Clear(&(t->Nodes)); - t->Root = NULL; - t->FreeList = NULL; + t->Nodes.Clear(&(t->Nodes)); + t->Root = NULL; + t->FreeList = NULL; } PUBFUNC void Bst_Free(Bst *t) @@ -316,12 +316,12 @@ PUBFUNC void Bst_Free(Bst *t) int Bst_Init(Bst *t, int ElementLength, CompareFunc Compare) { - t->Compare = Compare; - t->Root = NULL; - t->FreeList = NULL; - t->ElementLength = ElementLength; + t->Compare = Compare; + t->Root = NULL; + t->FreeList = NULL; + t->ElementLength = ElementLength; - if( StableBuffer_Init(&(t->Nodes)) != 0 ) + if( StableBuffer_Init(&(t->Nodes)) != 0 ) { return -497; } @@ -335,5 +335,5 @@ int Bst_Init(Bst *t, int ElementLength, CompareFunc Compare) t->Search = Bst_Search; t->Successor = Bst_Successor; - return 0; + return 0; } diff --git a/bst.h b/bst.h index 9c6037a6..cf64293d 100755 --- a/bst.h +++ b/bst.h @@ -8,9 +8,9 @@ typedef struct _Bst_NodeHead Bst_NodeHead; struct _Bst_NodeHead{ - Bst_NodeHead *Parent; - Bst_NodeHead *Left; - Bst_NodeHead *Right; + Bst_NodeHead *Parent; + Bst_NodeHead *Left; + Bst_NodeHead *Right; }; typedef struct _Bst Bst; @@ -19,16 +19,16 @@ typedef struct _Bst Bst; typedef int (*Bst_Enum_Callback)(Bst *t, const void *Data, void *Arg); struct _Bst { - PRIMEMB StableBuffer Nodes; - PRIMEMB int ElementLength; - PRIMEMB Bst_NodeHead *Root; - PRIMEMB Bst_NodeHead *FreeList; - PRIMEMB CompareFunc Compare; - - PUBMEMB const void *(*Add)(Bst *t, const void *Data); - PUBMEMB const void *(*Search)(Bst *t, const void *Key, const void *Last); - PUBMEMB void (*Enum)(Bst *t, Bst_Enum_Callback cb, void *Arg); - PUBMEMB const void *(*Minimum)(Bst *t, const void *Subtree); + PRIMEMB StableBuffer Nodes; + PRIMEMB int ElementLength; + PRIMEMB Bst_NodeHead *Root; + PRIMEMB Bst_NodeHead *FreeList; + PRIMEMB CompareFunc Compare; + + PUBMEMB const void *(*Add)(Bst *t, const void *Data); + PUBMEMB const void *(*Search)(Bst *t, const void *Key, const void *Last); + PUBMEMB void (*Enum)(Bst *t, Bst_Enum_Callback cb, void *Arg); + PUBMEMB const void *(*Minimum)(Bst *t, const void *Subtree); PUBMEMB const void *(*Successor)(Bst *t, const void *Last); PUBMEMB void (*Delete)(Bst *t, const void *Node); PUBMEMB void (*Reset)(Bst *t); diff --git a/cacheht.c b/cacheht.c index a8942add..d45ebba6 100755 --- a/cacheht.c +++ b/cacheht.c @@ -5,279 +5,279 @@ #include "utils.h" typedef struct _Cht_Slot{ - int32_t Next; + int32_t Next; } Cht_Slot; static int CacheHT_CalculateSlotCount(int CacheSize) { - int PreValue; - if( CacheSize < 1048576 ) - { - PreValue = CacheSize / 4979 - 18; - } else { - PreValue = pow(log((double)CacheSize), 2); - } - - return ROUND(PreValue, 10) + 7; + int PreValue; + if( CacheSize < 1048576 ) + { + PreValue = CacheSize / 4979 - 18; + } else { + PreValue = pow(log((double)CacheSize), 2); + } + + return ROUND(PreValue, 10) + 7; } int CacheHT_Init(CacheHT *h, char *BaseAddr, int CacheSize) { - int loop; + int loop; - h->Slots.Used = CacheHT_CalculateSlotCount(CacheSize); - h->Slots.DataLength = sizeof(Cht_Slot); - h->Slots.Data = BaseAddr + CacheSize - (h->Slots.DataLength) * (h->Slots.Used); - h->Slots.Allocated = h->Slots.Used; + h->Slots.Used = CacheHT_CalculateSlotCount(CacheSize); + h->Slots.DataLength = sizeof(Cht_Slot); + h->Slots.Data = BaseAddr + CacheSize - (h->Slots.DataLength) * (h->Slots.Used); + h->Slots.Allocated = h->Slots.Used; - for(loop = 0; loop != h->Slots.Allocated; ++loop) - { - ((Cht_Slot *)Array_GetBySubscript(&(h->Slots), loop))->Next = -1; - } + for(loop = 0; loop != h->Slots.Allocated; ++loop) + { + ((Cht_Slot *)Array_GetBySubscript(&(h->Slots), loop))->Next = -1; + } - h->NodeChunk.DataLength = sizeof(Cht_Node); - h->NodeChunk.Data = h->Slots.Data - h->NodeChunk.DataLength; - h->NodeChunk.Used = 0; - h->NodeChunk.Allocated = -1; + h->NodeChunk.DataLength = sizeof(Cht_Node); + h->NodeChunk.Data = h->Slots.Data - h->NodeChunk.DataLength; + h->NodeChunk.Used = 0; + h->NodeChunk.Allocated = -1; - h->FreeList = -1; + h->FreeList = -1; - return 0; + return 0; } int CacheHT_ReInit(CacheHT *h, char *BaseAddr, int CacheSize) { - h->Slots.Data = BaseAddr + CacheSize - (h->Slots.DataLength) * (h->Slots.Used); - h->NodeChunk.Data = h->Slots.Data - h->NodeChunk.DataLength; + h->Slots.Data = BaseAddr + CacheSize - (h->Slots.DataLength) * (h->Slots.Used); + h->NodeChunk.Data = h->Slots.Data - h->NodeChunk.DataLength; - return 0; + return 0; } static int CacheHT_CreateNewNode(CacheHT *h, uint32_t ChunkSize, Cht_Node **Out, void *Boundary) { - int NewNode_i; - Cht_Node *NewNode; + int NewNode_i; + Cht_Node *NewNode; - Array *NodeChunk = &(h->NodeChunk); + Array *NodeChunk = &(h->NodeChunk); - NewNode_i = Array_PushBack(NodeChunk, NULL, Boundary); - if( NewNode_i < 0 ) - { - return -1; - } + NewNode_i = Array_PushBack(NodeChunk, NULL, Boundary); + if( NewNode_i < 0 ) + { + return -1; + } - NewNode = (Cht_Node *)Array_GetBySubscript(NodeChunk, NewNode_i); - NewNode->Next = -1; + NewNode = (Cht_Node *)Array_GetBySubscript(NodeChunk, NewNode_i); + NewNode->Next = -1; - NewNode->Length = ChunkSize; + NewNode->Length = ChunkSize; - if( Out != NULL ) - { - *Out = NewNode; - } + if( Out != NULL ) + { + *Out = NewNode; + } - return NewNode_i; + return NewNode_i; } -int32_t CacheHT_FindUnusedNode(CacheHT *h, - uint32_t ChunkSize, - Cht_Node **Out, - void *Boundary, - BOOL *NewCreated - ) +int32_t CacheHT_FindUnusedNode(CacheHT *h, + uint32_t ChunkSize, + Cht_Node **Out, + void *Boundary, + BOOL *NewCreated + ) { - int32_t Subscript = h->FreeList; - Cht_Node *FirstNode = NULL; - Cht_Node *SecondNode = NULL; - - Array *NodeChunk = &(h->NodeChunk); - - while ( Subscript >= 0 ) - { - FirstNode = SecondNode; - SecondNode = (Cht_Node *)Array_GetBySubscript(NodeChunk, Subscript); - if( SecondNode->Length == ChunkSize ) - { - if( FirstNode == NULL ) - { - h->FreeList = SecondNode->Next; - } else { - FirstNode->Next = SecondNode->Next; - } - - SecondNode->Next = -1; - - if( Out != NULL ) - { - *Out = SecondNode; - } - - *NewCreated = FALSE; - - return Subscript; - } - - Subscript = SecondNode->Next; - } - - *NewCreated = TRUE; - return CacheHT_CreateNewNode(h, ChunkSize, Out, Boundary); + int32_t Subscript = h->FreeList; + Cht_Node *FirstNode = NULL; + Cht_Node *SecondNode = NULL; + + Array *NodeChunk = &(h->NodeChunk); + + while ( Subscript >= 0 ) + { + FirstNode = SecondNode; + SecondNode = (Cht_Node *)Array_GetBySubscript(NodeChunk, Subscript); + if( SecondNode->Length == ChunkSize ) + { + if( FirstNode == NULL ) + { + h->FreeList = SecondNode->Next; + } else { + FirstNode->Next = SecondNode->Next; + } + + SecondNode->Next = -1; + + if( Out != NULL ) + { + *Out = SecondNode; + } + + *NewCreated = FALSE; + + return Subscript; + } + + Subscript = SecondNode->Next; + } + + *NewCreated = TRUE; + return CacheHT_CreateNewNode(h, ChunkSize, Out, Boundary); } static void ThereIsAnEnd(CacheHT *h, int Slot_i, Cht_Slot *Slot) { - int i = Slot->Next; - Cht_Node *Node; + int i = Slot->Next; + Cht_Node *Node; - while( i >= 0 ) - { - Node = Array_GetBySubscript(&(h->NodeChunk), i); + while( i >= 0 ) + { + Node = Array_GetBySubscript(&(h->NodeChunk), i); - if( Node->Slot != Slot_i ) - { - printf("--------------------ERROR\n"); - } + if( Node->Slot != Slot_i ) + { + printf("--------------------ERROR\n"); + } - i = Node->Next; - } + i = Node->Next; + } } -int CacheHT_InsertToSlot(CacheHT *h, - const char *Key, - int Node_index, - Cht_Node *Node, - uint32_t *HashValue - ) +int CacheHT_InsertToSlot(CacheHT *h, + const char *Key, + int Node_index, + Cht_Node *Node, + uint32_t *HashValue + ) { - int Slot_i; - Cht_Slot *Slot; + int Slot_i; + Cht_Slot *Slot; - if( h == NULL || Key == NULL || Node_index < 0 || Node == NULL ) - return -1; + if( h == NULL || Key == NULL || Node_index < 0 || Node == NULL ) + return -1; - if( HashValue != NULL ) - { - Slot_i = (*HashValue) % (h->Slots.Allocated); - } else { - Slot_i = HASH(Key, 0) % (h->Slots.Allocated); - } + if( HashValue != NULL ) + { + Slot_i = (*HashValue) % (h->Slots.Allocated); + } else { + Slot_i = HASH(Key, 0) % (h->Slots.Allocated); + } - Node->Slot = Slot_i; + Node->Slot = Slot_i; - Slot = (Cht_Slot *)Array_GetBySubscript(&(h->Slots), Slot_i); - if( Slot == NULL ) - return -2; + Slot = (Cht_Slot *)Array_GetBySubscript(&(h->Slots), Slot_i); + if( Slot == NULL ) + return -2; - Node->Next = Slot->Next; - Slot->Next = Node_index; + Node->Next = Slot->Next; + Slot->Next = Node_index; - return 0; + return 0; } static Cht_Node *CacheHT_FindPredecesor(CacheHT *h, Cht_Slot *Slot, int32_t SubScriptOfNode) { - int Next = Slot->Next; - Cht_Node *Node; - - if( Next == SubScriptOfNode ) - { - return NULL; - } - - while( Next >= 0 ) - { - Node = Array_GetBySubscript(&(h->NodeChunk), Next); - Next = Node->Next; - - if( Next == SubScriptOfNode ) - { - return Node; - } - } - - return NULL; + int Next = Slot->Next; + Cht_Node *Node; + + if( Next == SubScriptOfNode ) + { + return NULL; + } + + while( Next >= 0 ) + { + Node = Array_GetBySubscript(&(h->NodeChunk), Next); + Next = Node->Next; + + if( Next == SubScriptOfNode ) + { + return Node; + } + } + + return NULL; } int CacheHT_RemoveFromSlot(CacheHT *h, int32_t SubScriptOfNode, Cht_Node *Node) { - Array *NodeChunk = &(h->NodeChunk); - Cht_Slot *Slot; - Cht_Node *Predecesor; - - if( Node->Slot < 0 ) - { - return 0; - } - - Slot = (Cht_Slot *)Array_GetBySubscript(&(h->Slots), Node->Slot); - if( Slot == NULL ) - { - return -1; - } - - Predecesor = CacheHT_FindPredecesor(h, Slot, SubScriptOfNode); - if( Predecesor == NULL ) - { - Slot->Next = Node->Next; - } else { - Predecesor->Next = Node->Next; - } - - /* If this node is not the last one of NodeChunk, add it into free list, - * or simply delete it from NodeChunk - */ - if( SubScriptOfNode != NodeChunk->Used - 1 ) - { - Node->Next = h->FreeList; - h->FreeList = SubScriptOfNode; - Node->Slot = -1; - } else { - --(NodeChunk->Used); - } - - return 0; + Array *NodeChunk = &(h->NodeChunk); + Cht_Slot *Slot; + Cht_Node *Predecesor; + + if( Node->Slot < 0 ) + { + return 0; + } + + Slot = (Cht_Slot *)Array_GetBySubscript(&(h->Slots), Node->Slot); + if( Slot == NULL ) + { + return -1; + } + + Predecesor = CacheHT_FindPredecesor(h, Slot, SubScriptOfNode); + if( Predecesor == NULL ) + { + Slot->Next = Node->Next; + } else { + Predecesor->Next = Node->Next; + } + + /* If this node is not the last one of NodeChunk, add it into free list, + * or simply delete it from NodeChunk + */ + if( SubScriptOfNode != NodeChunk->Used - 1 ) + { + Node->Next = h->FreeList; + h->FreeList = SubScriptOfNode; + Node->Slot = -1; + } else { + --(NodeChunk->Used); + } + + return 0; } Cht_Node *CacheHT_Get(CacheHT *h, const char *Key, Cht_Node *Start, uint32_t *HashValue) { - Cht_Node *Node; + Cht_Node *Node; - if( h == NULL || Key == NULL) - return NULL; + if( h == NULL || Key == NULL) + return NULL; - if( Start == NULL ) - { - int Slot_i; - Cht_Slot *Slot; + if( Start == NULL ) + { + int Slot_i; + Cht_Slot *Slot; - if( HashValue != NULL ) - { - Slot_i = (*HashValue) % (h->Slots.Allocated); - } else { - Slot_i = HASH(Key, 0) % (h->Slots.Allocated); - } + if( HashValue != NULL ) + { + Slot_i = (*HashValue) % (h->Slots.Allocated); + } else { + Slot_i = HASH(Key, 0) % (h->Slots.Allocated); + } - Slot = (Cht_Slot *)Array_GetBySubscript(&(h->Slots), Slot_i); + Slot = (Cht_Slot *)Array_GetBySubscript(&(h->Slots), Slot_i); - Node = (Cht_Node *)Array_GetBySubscript(&(h->NodeChunk), Slot->Next); - if( Node == NULL ) - return NULL; + Node = (Cht_Node *)Array_GetBySubscript(&(h->NodeChunk), Slot->Next); + if( Node == NULL ) + return NULL; - return Node; + return Node; - } else { - Node = (Cht_Node *)Array_GetBySubscript(&(h->NodeChunk), Start->Next); - if( Node == NULL ) - return NULL; + } else { + Node = (Cht_Node *)Array_GetBySubscript(&(h->NodeChunk), Start->Next); + if( Node == NULL ) + return NULL; - return Node; - } + return Node; + } } void CacheHT_Free(CacheHT *h) { - Array_Free(&(h->NodeChunk)); - Array_Free(&(h->Slots)); - h->FreeList = -1; + Array_Free(&(h->NodeChunk)); + Array_Free(&(h->Slots)); + h->FreeList = -1; } diff --git a/cacheht.h b/cacheht.h index ba4a5b79..91f81540 100755 --- a/cacheht.h +++ b/cacheht.h @@ -5,37 +5,37 @@ #include "array.h" typedef struct _Cht_Node{ - int32_t Slot; - int32_t Next; - int32_t Offset; - uint32_t TTL; - time_t TimeAdded; - uint32_t Length; + int32_t Slot; + int32_t Next; + int32_t Offset; + uint32_t TTL; + time_t TimeAdded; + uint32_t Length; } Cht_Node; typedef struct _HashTable{ - Array NodeChunk; - Array Slots; - int32_t FreeList; + Array NodeChunk; + Array Slots; + int32_t FreeList; }CacheHT; int CacheHT_Init(CacheHT *h, char *BaseAddr, int CacheSize); int CacheHT_ReInit(CacheHT *h, char *BaseAddr, int CacheSize); -int32_t CacheHT_FindUnusedNode(CacheHT *h, - uint32_t ChunkSize, - Cht_Node **Out, - void *Boundary, - BOOL *NewCreated - ); - -int CacheHT_InsertToSlot(CacheHT *h, - const char *Key, - int Node_index, - Cht_Node *Node, - uint32_t *HashValue - ); +int32_t CacheHT_FindUnusedNode(CacheHT *h, + uint32_t ChunkSize, + Cht_Node **Out, + void *Boundary, + BOOL *NewCreated + ); + +int CacheHT_InsertToSlot(CacheHT *h, + const char *Key, + int Node_index, + Cht_Node *Node, + uint32_t *HashValue + ); int CacheHT_RemoveFromSlot(CacheHT *h, int32_t SubScriptOfNode, Cht_Node *Node); diff --git a/cachettlcrtl.c b/cachettlcrtl.c index bdc98181..e4b392c9 100755 --- a/cachettlcrtl.c +++ b/cachettlcrtl.c @@ -5,102 +5,102 @@ int CacheTtlCrtl_Init(CacheTtlCtrl *c) { - return StringChunk_Init((StringChunk *)c, NULL); + return StringChunk_Init((StringChunk *)c, NULL); } int CacheTtlCrtl_Add(CacheTtlCtrl *c, const char *Domain, int State, uint32_t Coefficient, uint32_t Increment, int Infection) { - CtrlContent cc = {State, Coefficient, Increment, Infection}; + CtrlContent cc = {State, Coefficient, Increment, Infection}; - if( State == TTL_STATE_FIXED ) - { - cc.Coefficient = 0; - } + if( State == TTL_STATE_FIXED ) + { + cc.Coefficient = 0; + } - return StringChunk_Add_Domain((StringChunk *)c, Domain, (const char *)&cc, sizeof(CtrlContent)); + return StringChunk_Add_Domain((StringChunk *)c, Domain, (const char *)&cc, sizeof(CtrlContent)); } int CacheTtlCrtl_Add_From_String(CacheTtlCtrl *c, const char *Rule) { - char Domain[128], Cmd[16], Arg[64]; - int State; - uint32_t Coefficient = 0; - uint32_t Increment = 0; - int Infection = TTL_CTRL_INFECTION_AGGRESSIVLY; - - sscanf(Rule, "%127s%15s%64s", Domain, Cmd, Arg); - - if( Cmd[0] == '$' ) - { - if( Cmd[1] == '$' ) - { - Infection = TTL_CTRL_INFECTION_NONE; - memmove(Cmd, Cmd + 2, sizeof(Cmd) - 2); - } else { - Infection = TTL_CTRL_INFECTION_PASSIVLY; - memmove(Cmd, Cmd + 1, sizeof(Cmd) - 1); - } - } else { - Infection = TTL_CTRL_INFECTION_AGGRESSIVLY; - } - - #define IS_STATE(s) (strncmp(Cmd, (s), strlen(s)) == 0) - if( IS_STATE("orig") ) - { - State = TTL_STATE_ORIGINAL; - } else if( IS_STATE("nocache") ) - { - State = TTL_STATE_NO_CACHE; - } else if( IS_STATE("fixed") ) - { - State = TTL_STATE_FIXED; - Coefficient = 0; - sscanf(Arg, "%u", &Increment); - } else if( IS_STATE("vari") ) - { - State = TTL_STATE_VARIABLE; - sscanf(Arg, "%ux+%u", &Coefficient, &Increment); - } else { - ERRORMSG("Invalid `CacheControl' option : %s\n", Rule); - return -1; - } - - return CacheTtlCrtl_Add(c, Domain, State, Coefficient, Increment, Infection); + char Domain[128], Cmd[16], Arg[64]; + int State; + uint32_t Coefficient = 0; + uint32_t Increment = 0; + int Infection = TTL_CTRL_INFECTION_AGGRESSIVLY; + + sscanf(Rule, "%127s%15s%64s", Domain, Cmd, Arg); + + if( Cmd[0] == '$' ) + { + if( Cmd[1] == '$' ) + { + Infection = TTL_CTRL_INFECTION_NONE; + memmove(Cmd, Cmd + 2, sizeof(Cmd) - 2); + } else { + Infection = TTL_CTRL_INFECTION_PASSIVLY; + memmove(Cmd, Cmd + 1, sizeof(Cmd) - 1); + } + } else { + Infection = TTL_CTRL_INFECTION_AGGRESSIVLY; + } + + #define IS_STATE(s) (strncmp(Cmd, (s), strlen(s)) == 0) + if( IS_STATE("orig") ) + { + State = TTL_STATE_ORIGINAL; + } else if( IS_STATE("nocache") ) + { + State = TTL_STATE_NO_CACHE; + } else if( IS_STATE("fixed") ) + { + State = TTL_STATE_FIXED; + Coefficient = 0; + sscanf(Arg, "%u", &Increment); + } else if( IS_STATE("vari") ) + { + State = TTL_STATE_VARIABLE; + sscanf(Arg, "%ux+%u", &Coefficient, &Increment); + } else { + ERRORMSG("Invalid `CacheControl' option : %s\n", Rule); + return -1; + } + + return CacheTtlCrtl_Add(c, Domain, State, Coefficient, Increment, Infection); } int CacheTtlCrtl_Add_From_StringList(CacheTtlCtrl *c, StringList *sl) { - const char *Itr = NULL; - StringListIterator sli; + const char *Itr = NULL; + StringListIterator sli; - if( sl == NULL ) + if( sl == NULL ) { return 0; } - if( StringListIterator_Init(&sli, sl) != 0 ) + if( StringListIterator_Init(&sli, sl) != 0 ) { return -1; } - Itr = sli.Next(&sli); - while( Itr != NULL ) - { - CacheTtlCrtl_Add_From_String(c, Itr); + Itr = sli.Next(&sli); + while( Itr != NULL ) + { + CacheTtlCrtl_Add_From_String(c, Itr); - Itr = sli.Next(&sli); - } + Itr = sli.Next(&sli); + } - return 0; + return 0; } const CtrlContent *CacheTtlCrtl_Get(CacheTtlCtrl *c, const char *Domain) { - CtrlContent *ret = NULL; - if( StringChunk_Domain_Match((StringChunk *)c, Domain, NULL, (void **)&(ret)) == TRUE ) - { - return ret; - } else { - return NULL; - } + CtrlContent *ret = NULL; + if( StringChunk_Domain_Match((StringChunk *)c, Domain, NULL, (void **)&(ret)) == TRUE ) + { + return ret; + } else { + return NULL; + } } diff --git a/cachettlcrtl.h b/cachettlcrtl.h index 168d6289..c1d32319 100755 --- a/cachettlcrtl.h +++ b/cachettlcrtl.h @@ -3,20 +3,20 @@ #include "stringchunk.h" -#define TTL_STATE_NO_CACHE 0 -#define TTL_STATE_ORIGINAL (-1) -#define TTL_STATE_FIXED (1) -#define TTL_STATE_VARIABLE (2) +#define TTL_STATE_NO_CACHE 0 +#define TTL_STATE_ORIGINAL (-1) +#define TTL_STATE_FIXED (1) +#define TTL_STATE_VARIABLE (2) -#define TTL_CTRL_INFECTION_AGGRESSIVLY 0 -#define TTL_CTRL_INFECTION_PASSIVLY (1) -#define TTL_CTRL_INFECTION_NONE (2) +#define TTL_CTRL_INFECTION_AGGRESSIVLY 0 +#define TTL_CTRL_INFECTION_PASSIVLY (1) +#define TTL_CTRL_INFECTION_NONE (2) typedef struct _CtrlContent { - int State; - uint32_t Coefficient; - uint32_t Increment; - int Infection; + int State; + uint32_t Coefficient; + uint32_t Increment; + int Infection; } CtrlContent; /* Final TTL = Coefficient * State + Increment, if State is positive. */ diff --git a/common.h b/common.h index e38be1ff..574a79ae 100755 --- a/common.h +++ b/common.h @@ -3,7 +3,7 @@ #include #ifdef HAVE_CONFIG_H - #include "config.h" + #include "config.h" #endif /* HAVE_CONFIG_H */ /* There are many differeces between Linux and Windows. @@ -19,279 +19,279 @@ #define _WIN32_WINNT 0x0600 #endif - #include - #include /* fd_set, struct sockaddr_in, */ - #include /* For many things */ - #include /* Some internet API, include InternetOpen(), InternetOpenUrl(), etc. */ - #include /* PathMatchSpec() */ - #include /* struct sockaddr_in6 */ + #include + #include /* fd_set, struct sockaddr_in, */ + #include /* For many things */ + #include /* Some internet API, include InternetOpen(), InternetOpenUrl(), etc. */ + #include /* PathMatchSpec() */ + #include /* struct sockaddr_in6 */ - /* In Linux, the last prarmeter of 'send' is mostly MSG_NOSIGNAL(0x4000) (defined in linux headers), - * but in Windows, no this macro. And this prarmeter is zero, mostly. - * So we define this macro for Windows. - */ + /* In Linux, the last prarmeter of 'send' is mostly MSG_NOSIGNAL(0x4000) (defined in linux headers), + * but in Windows, no this macro. And this prarmeter is zero, mostly. + * So we define this macro for Windows. + */ - typedef int socklen_t; + typedef int socklen_t; - /* In Windows, the indetifer of a thread is just a 'HANDLE'. */ - typedef HANDLE ThreadHandle; - /* And Mutex */ - typedef HANDLE MutexHandle; + /* In Windows, the indetifer of a thread is just a 'HANDLE'. */ + typedef HANDLE ThreadHandle; + /* And Mutex */ + typedef HANDLE MutexHandle; - /* Files */ - typedef HANDLE FileHandle; - #define INVALID_FILE ((FileHandle)NULL) - typedef HANDLE MappingHandle; - #define INVALID_MAP ((MappingHandle)NULL) - #define INVALID_MAPPING_FILE (NULL) + /* Files */ + typedef HANDLE FileHandle; + #define INVALID_FILE ((FileHandle)NULL) + typedef HANDLE MappingHandle; + #define INVALID_MAP ((MappingHandle)NULL) + #define INVALID_MAPPING_FILE (NULL) /* TCP_TIME_OUT, used as a return value */ - #define TCP_TIME_OUT WSAETIMEDOUT - - #define GET_LAST_ERROR() (WSAGetLastError()) - #define SET_LAST_ERROR(i) (WSASetLastError(i)) - - /* Close a socket */ - #define CLOSE_SOCKET(s) (closesocket(s)) - - /* Threading */ - #define CREATE_THREAD(func_ptr, para_ptr, result_holder) (result_holder) = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)(func_ptr), (para_ptr), 0, NULL); - #define EXIT_THREAD(r) return (r) - #define DETACH_THREAD(t) CloseHandle(t) - - /* Mutex */ - #define CREATE_MUTEX(m) ((m) = CreateMutex(NULL, FALSE, NULL)) - #define GET_MUTEX(m) (WaitForSingleObject((m), INFINITE)) - #define GET_MUTEX_TRY(m) (WaitForSingleObject((m), 0)) - #define RELEASE_MUTEX(m) (ReleaseMutex(m)) - #define DESTROY_MUTEX(m) (CloseHandle(m)) - #define GET_MUTEX_FAILED WAIT_TIMEOUT /* Used as return value */ - - /* CRITICAL_SECTION */ - #define CRITICAL_SECTION_INIT(c, spin_count) (InitializeCriticalSectionAndSpinCount(&(c), (spin_count))) - #define ENTER_CRITICAL_SECTION(c) (EnterCriticalSection(&(c))) - #define ENTER_CRITICAL_SECTION_TRY(c) (TryEnterCriticalSection(&(c))) - #define CRITICAL_SECTION_TRY_SUCCEED(ret) ((ret) != 0) - #define LEAVE_CRITICAL_SECTION(c) (LeaveCriticalSection(&(c))) - #define DELETE_CRITICAL_SECTION(c) (DeleteCriticalSection(&(c))) + #define TCP_TIME_OUT WSAETIMEDOUT + + #define GET_LAST_ERROR() (WSAGetLastError()) + #define SET_LAST_ERROR(i) (WSASetLastError(i)) + + /* Close a socket */ + #define CLOSE_SOCKET(s) (closesocket(s)) + + /* Threading */ + #define CREATE_THREAD(func_ptr, para_ptr, result_holder) (result_holder) = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)(func_ptr), (para_ptr), 0, NULL); + #define EXIT_THREAD(r) return (r) + #define DETACH_THREAD(t) CloseHandle(t) + + /* Mutex */ + #define CREATE_MUTEX(m) ((m) = CreateMutex(NULL, FALSE, NULL)) + #define GET_MUTEX(m) (WaitForSingleObject((m), INFINITE)) + #define GET_MUTEX_TRY(m) (WaitForSingleObject((m), 0)) + #define RELEASE_MUTEX(m) (ReleaseMutex(m)) + #define DESTROY_MUTEX(m) (CloseHandle(m)) + #define GET_MUTEX_FAILED WAIT_TIMEOUT /* Used as return value */ + + /* CRITICAL_SECTION */ + #define CRITICAL_SECTION_INIT(c, spin_count) (InitializeCriticalSectionAndSpinCount(&(c), (spin_count))) + #define ENTER_CRITICAL_SECTION(c) (EnterCriticalSection(&(c))) + #define ENTER_CRITICAL_SECTION_TRY(c) (TryEnterCriticalSection(&(c))) + #define CRITICAL_SECTION_TRY_SUCCEED(ret) ((ret) != 0) + #define LEAVE_CRITICAL_SECTION(c) (LeaveCriticalSection(&(c))) + #define DELETE_CRITICAL_SECTION(c) (DeleteCriticalSection(&(c))) /* File and mapping handles*/ - #define OPEN_FILE(file) CreateFile((file), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL) - #define CREATE_FILE_MAPPING(handle, size) CreateFileMapping((handle), NULL, PAGE_READWRITE, 0, size, NULL); - #define MPA_FILE(handle, size) MapViewOfFile((handle), FILE_MAP_WRITE, 0, 0, 0) + #define OPEN_FILE(file) CreateFile((file), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL) + #define CREATE_FILE_MAPPING(handle, size) CreateFileMapping((handle), NULL, PAGE_READWRITE, 0, size, NULL); + #define MPA_FILE(handle, size) MapViewOfFile((handle), FILE_MAP_WRITE, 0, 0, 0) - #define UNMAP_FILE(start, size) UnmapViewOfFile(start) - #define DESTROY_MAPPING(handle) CloseHandle(handle) - #define CLOSE_FILE(handle) CloseHandle(handle) + #define UNMAP_FILE(start, size) UnmapViewOfFile(start) + #define DESTROY_MAPPING(handle) CloseHandle(handle) + #define CLOSE_FILE(handle) CloseHandle(handle) - #define PATH_SLASH_CH '\\' - #define PATH_SLASH_STR "\\" + #define PATH_SLASH_CH '\\' + #define PATH_SLASH_STR "\\" /* Fill Address */ - #define FILL_ADDR4(addr_struct, family, address_string, port) (addr_struct).sin_family = (family); \ - (addr_struct).sin_addr.S_un.S_addr = inet_addr(address_string); \ - (addr_struct).sin_port = htons(port); - /* Suspend current thread for some milliseconds */ - #define SLEEP(i) (Sleep(i)) + #define FILL_ADDR4(addr_struct, family, address_string, port) (addr_struct).sin_family = (family); \ + (addr_struct).sin_addr.S_un.S_addr = inet_addr(address_string); \ + (addr_struct).sin_port = htons(port); + /* Suspend current thread for some milliseconds */ + #define SLEEP(i) (Sleep(i)) - #define GET_TEMP_DIR() getenv("TEMP") + #define GET_TEMP_DIR() getenv("TEMP") - #define GET_THREAD_ID() ((int)GetCurrentThreadId()) + #define GET_THREAD_ID() ((int)GetCurrentThreadId()) - /* Wildcard match function */ - #define WILDCARD_MATCH(p, s) PathMatchSpec((s), (p)) - #define WILDCARD_MATCHED TRUE /* Used as return value */ + /* Wildcard match function */ + #define WILDCARD_MATCH(p, s) PathMatchSpec((s), (p)) + #define WILDCARD_MATCHED TRUE /* Used as return value */ - #define CONNECT_FUNCTION_BLOCKED WSAEWOULDBLOCK + #define CONNECT_FUNCTION_BLOCKED WSAEWOULDBLOCK - typedef short sa_family_t; + typedef short sa_family_t; - #define ExitThisThread() (ExitThread(0)) + #define ExitThisThread() (ExitThread(0)) #else /* For Linux below */ - #include /* For struct 'sockaddr_in' */ + #include /* For struct 'sockaddr_in' */ - /* For function 'socket', 'bind', 'connect', 'send', 'recv', - * 'sendto', 'recvfrom', 'setsockopt', 'shutdown'. */ - #include + /* For function 'socket', 'bind', 'connect', 'send', 'recv', + * 'sendto', 'recvfrom', 'setsockopt', 'shutdown'. */ + #include - #include /* For function 'close' , 'sleep' */ - #include /* For extern variable 'errno'. */ - #include /* For function 'inet_addr'. */ - #include /* Multithread support. */ + #include /* For function 'close' , 'sleep' */ + #include /* For extern variable 'errno'. */ + #include /* For function 'inet_addr'. */ + #include /* Multithread support. */ - #include /* struct stat */ - #include /* stat() */ + #include /* struct stat */ + #include /* stat() */ - #include /* mmap */ - #include + #include /* mmap */ + #include - #ifdef HAVE_SYS_SYSCALL_H - #include /* syscall */ - #endif /* HAVE_SYS_SYSCALL_H */ + #ifdef HAVE_SYS_SYSCALL_H + #include /* syscall */ + #endif /* HAVE_SYS_SYSCALL_H */ - #include /* struct passwd */ + #include /* struct passwd */ - #include /* fnmatch() */ + #include /* fnmatch() */ - /* In Linux, the type of socket is 'int'. */ - typedef int SOCKET; + /* In Linux, the type of socket is 'int'. */ + typedef int SOCKET; - /* We use pthread to implement multi threads */ - /* The indetifer of pthread is 'pthread_t'. */ - typedef pthread_t ThreadHandle; - /* And mutex */ - typedef pthread_mutex_t MutexHandle; - /* spin lock */ + /* We use pthread to implement multi threads */ + /* The indetifer of pthread is 'pthread_t'. */ + typedef pthread_t ThreadHandle; + /* And mutex */ + typedef pthread_mutex_t MutexHandle; + /* spin lock */ #ifdef HAVE_PTHREAD_SPIN_INIT - typedef pthread_spinlock_t SpinHandle; + typedef pthread_spinlock_t SpinHandle; #else - typedef pthread_mutex_t SpinHandle; + typedef pthread_mutex_t SpinHandle; #endif - /* There are so many HANDLEs are just ints in Linux. */ - typedef int FileHandle; /* The type of return value of open() */ - #define INVALID_FILE ((FileHandle)(-1)) + /* There are so many HANDLEs are just ints in Linux. */ + typedef int FileHandle; /* The type of return value of open() */ + #define INVALID_FILE ((FileHandle)(-1)) - typedef int MappingHandle; - #define INVALID_MAP ((MappingHandle)(-1)) - #define INVALID_MAPPING_FILE ((void *)(-1)) + typedef int MappingHandle; + #define INVALID_MAP ((MappingHandle)(-1)) + #define INVALID_MAPPING_FILE ((void *)(-1)) /* TCP_TIME_OUT, used as a return value */ - #define TCP_TIME_OUT EAGAIN + #define TCP_TIME_OUT EAGAIN - #define GET_LAST_ERROR() errno - #define SET_LAST_ERROR(i) (errno = (i)) + #define GET_LAST_ERROR() errno + #define SET_LAST_ERROR(i) (errno = (i)) - /* These are defined in 'windows.h'. */ - #define INVALID_SOCKET ((SOCKET)(~0)) - #define SOCKET_ERROR (-1) + /* These are defined in 'windows.h'. */ + #define INVALID_SOCKET ((SOCKET)(~0)) + #define SOCKET_ERROR (-1) - /* Close a socket */ - #define CLOSE_SOCKET(s) (close(s)) + /* Close a socket */ + #define CLOSE_SOCKET(s) (close(s)) - /* Boolean */ - #define BOOL int - #define FALSE 0 - #define TRUE (!0) + /* Boolean */ + #define BOOL int + #define FALSE 0 + #define TRUE (!0) #ifndef SO_DONTLINGER - #define SO_DONTLINGER ((unsigned int) (~SO_LINGER)) + #define SO_DONTLINGER ((unsigned int) (~SO_LINGER)) #endif - /* pthread */ - #define CREATE_THREAD(func_ptr, para_ptr, return_value) (pthread_create(&return_value, NULL, (void *(*)())(func_ptr), (para_ptr))) - #define EXIT_THREAD(r) pthread_exit(r) - #define DETACH_THREAD(t) pthread_detach(t) + /* pthread */ + #define CREATE_THREAD(func_ptr, para_ptr, return_value) (pthread_create(&return_value, NULL, (void *(*)())(func_ptr), (para_ptr))) + #define EXIT_THREAD(r) pthread_exit(r) + #define DETACH_THREAD(t) pthread_detach(t) /* mutex */ - #define CREATE_MUTEX(m) (pthread_mutex_init(&(m), NULL)) - #define GET_MUTEX(m) (pthread_mutex_lock(&(m))) - #define GET_MUTEX_TRY(m) (pthread_mutex_trylock(&(m))) - #define RELEASE_MUTEX(m) (pthread_mutex_unlock(&(m))) - #define DESTROY_MUTEX(m) (pthread_mutex_destroy(&(m))) - #define GET_MUTEX_FAILED (!0) - - /* spin lock */ + #define CREATE_MUTEX(m) (pthread_mutex_init(&(m), NULL)) + #define GET_MUTEX(m) (pthread_mutex_lock(&(m))) + #define GET_MUTEX_TRY(m) (pthread_mutex_trylock(&(m))) + #define RELEASE_MUTEX(m) (pthread_mutex_unlock(&(m))) + #define DESTROY_MUTEX(m) (pthread_mutex_destroy(&(m))) + #define GET_MUTEX_FAILED (!0) + + /* spin lock */ #ifdef HAVE_PTHREAD_SPIN_INIT - #define CREATE_SPIN(s) (pthread_spin_init(&(s), PTHREAD_PROCESS_PRIVATE)) - #define LOCK_SPIN(s) (pthread_spin_lock(&(s))) - #define LOCK_SPIN_TRY(s) (pthread_spin_trylock(&(s))) - #define SPIN_TRY_SUCCEED(ret) ((ret) == 0) - #define UNLOCK_SPIN(s) (pthread_spin_unlock(&(s))) - #define DESTROY_SPIN(s) (pthread_spin_destroy(&(s))) + #define CREATE_SPIN(s) (pthread_spin_init(&(s), PTHREAD_PROCESS_PRIVATE)) + #define LOCK_SPIN(s) (pthread_spin_lock(&(s))) + #define LOCK_SPIN_TRY(s) (pthread_spin_trylock(&(s))) + #define SPIN_TRY_SUCCEED(ret) ((ret) == 0) + #define UNLOCK_SPIN(s) (pthread_spin_unlock(&(s))) + #define DESTROY_SPIN(s) (pthread_spin_destroy(&(s))) #else /*HAVE_PTHREAD_SPIN_INIT */ - #define CREATE_SPIN(s) (pthread_mutex_init(&(s), NULL)) - #define LOCK_SPIN(s) (pthread_mutex_lock(&(s))) - #define LOCK_SPIN_TRY(s) (pthread_mutex_trylock(&(s))) - #define SPIN_TRY_SUCCEED(ret) ((ret) == 0) - #define UNLOCK_SPIN(s) (pthread_mutex_unlock(&(s))) - #define DESTROY_SPIN(s) (pthread_mutex_destroy(&(s))) + #define CREATE_SPIN(s) (pthread_mutex_init(&(s), NULL)) + #define LOCK_SPIN(s) (pthread_mutex_lock(&(s))) + #define LOCK_SPIN_TRY(s) (pthread_mutex_trylock(&(s))) + #define SPIN_TRY_SUCCEED(ret) ((ret) == 0) + #define UNLOCK_SPIN(s) (pthread_mutex_unlock(&(s))) + #define DESTROY_SPIN(s) (pthread_mutex_destroy(&(s))) #endif /*HAVE_PTHREAD_SPIN_INIT */ /* File and Mapping */ /* In Linux, there is no a long process to map a file like Windows. */ - #define OPEN_FILE(file) (open((file), O_RDWR | O_CREAT, S_IRWXU)) - #define CREATE_FILE_MAPPING(handle, size) (lseek((handle), size, SEEK_SET), write((handle), "\0", 1), (handle)) - #define MPA_FILE(handle, size) (mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, (handle), 0)) - #define UNMAP_FILE(start, size) (munmap(start, size)) - #define DESTROY_MAPPING(handle) /* Nothing */ - #define CLOSE_FILE(handle) (close(handle)) + #define OPEN_FILE(file) (open((file), O_RDWR | O_CREAT, S_IRWXU)) + #define CREATE_FILE_MAPPING(handle, size) (lseek((handle), size, SEEK_SET), write((handle), "\0", 1), (handle)) + #define MPA_FILE(handle, size) (mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, (handle), 0)) + #define UNMAP_FILE(start, size) (munmap(start, size)) + #define DESTROY_MAPPING(handle) /* Nothing */ + #define CLOSE_FILE(handle) (close(handle)) - #define PATH_SLASH_CH '/' - #define PATH_SLASH_STR "/" + #define PATH_SLASH_CH '/' + #define PATH_SLASH_STR "/" - #define FILL_ADDR4(addr_struct, family, address_string, port) (addr_struct).sin_family = (family); \ - (addr_struct).sin_addr.s_addr = inet_addr(address_string); \ - (addr_struct).sin_port = htons(port); + #define FILL_ADDR4(addr_struct, family, address_string, port) (addr_struct).sin_family = (family); \ + (addr_struct).sin_addr.s_addr = inet_addr(address_string); \ + (addr_struct).sin_port = htons(port); /* Suspend current thread for some milliseconds */ - #define SLEEP(i) do \ - { \ - int Count = 1000; \ - do \ - { \ - usleep(i); \ - --Count; \ - } while( Count > 0 ); \ - } while( 0 ) + #define SLEEP(i) do \ + { \ + int Count = 1000; \ + do \ + { \ + usleep(i); \ + --Count; \ + } while( Count > 0 ); \ + } while( 0 ) /* As the name suggests */ - #define GET_TEMP_DIR() "/tmp" + #define GET_TEMP_DIR() "/tmp" #ifdef HAVE_SYS_SYSCALL_H - #define GET_THREAD_ID() syscall(__NR_gettid) + #define GET_THREAD_ID() syscall(__NR_gettid) #else /* HAVE_SYS_SYSCALL_H */ - #define GET_THREAD_ID() (-1) + #define GET_THREAD_ID() (-1) #endif /* HAVE_SYS_SYSCALL_H */ - #define WILDCARD_MATCH(p, s) fnmatch((p), (s), FNM_NOESCAPE) - #define WILDCARD_MATCHED 0 + #define WILDCARD_MATCH(p, s) fnmatch((p), (s), FNM_NOESCAPE) + #define WILDCARD_MATCHED 0 - #define CONNECT_FUNCTION_BLOCKED EINPROGRESS + #define CONNECT_FUNCTION_BLOCKED EINPROGRESS - #define ExitThisThread() (pthread_exit(NULL)) + #define ExitThisThread() (pthread_exit(NULL)) #endif /* WIN32 */ #ifdef WIN32 - typedef CRITICAL_SECTION EFFECTIVE_LOCK; - #define EFFECTIVE_LOCK_INIT(l) CRITICAL_SECTION_INIT((l), 1024) - #define EFFECTIVE_LOCK_GET(l) ENTER_CRITICAL_SECTION(l) - #define EFFECTIVE_LOCK_TRY_GET(l) ENTER_CRITICAL_SECTION_TRY(l) - #define EFFECTIVE_LOCK_TRY_SUCCEED(ret) CRITICAL_SECTION_TRY_SUCCEED(ret) - #define EFFECTIVE_LOCK_RELEASE(l) LEAVE_CRITICAL_SECTION(l) - #define EFFECTIVE_LOCK_DESTROY(l) DELETE_CRITICAL_SECTION(l) + typedef CRITICAL_SECTION EFFECTIVE_LOCK; + #define EFFECTIVE_LOCK_INIT(l) CRITICAL_SECTION_INIT((l), 1024) + #define EFFECTIVE_LOCK_GET(l) ENTER_CRITICAL_SECTION(l) + #define EFFECTIVE_LOCK_TRY_GET(l) ENTER_CRITICAL_SECTION_TRY(l) + #define EFFECTIVE_LOCK_TRY_SUCCEED(ret) CRITICAL_SECTION_TRY_SUCCEED(ret) + #define EFFECTIVE_LOCK_RELEASE(l) LEAVE_CRITICAL_SECTION(l) + #define EFFECTIVE_LOCK_DESTROY(l) DELETE_CRITICAL_SECTION(l) #else /* WIN32 */ - typedef SpinHandle EFFECTIVE_LOCK; - #define EFFECTIVE_LOCK_INIT(l) CREATE_SPIN(l) - #define EFFECTIVE_LOCK_GET(l) LOCK_SPIN(l) - #define EFFECTIVE_LOCK_TRY_GET(l) LOCK_SPIN_TRY(l) - #define EFFECTIVE_LOCK_TRY_SUCCEED(ret) SPIN_TRY_SUCCEED(ret) - #define EFFECTIVE_LOCK_RELEASE(l) UNLOCK_SPIN(l) - #define EFFECTIVE_LOCK_DESTROY(l) DESTROY_SPIN(l) + typedef SpinHandle EFFECTIVE_LOCK; + #define EFFECTIVE_LOCK_INIT(l) CREATE_SPIN(l) + #define EFFECTIVE_LOCK_GET(l) LOCK_SPIN(l) + #define EFFECTIVE_LOCK_TRY_GET(l) LOCK_SPIN_TRY(l) + #define EFFECTIVE_LOCK_TRY_SUCCEED(ret) SPIN_TRY_SUCCEED(ret) + #define EFFECTIVE_LOCK_RELEASE(l) UNLOCK_SPIN(l) + #define EFFECTIVE_LOCK_DESTROY(l) DESTROY_SPIN(l) #endif /* WIN32 */ #ifdef WIN32 - #define GetFileDirectory(out) (GetModulePath(out, sizeof(out))) + #define GetFileDirectory(out) (GetModulePath(out, sizeof(out))) #else /* WIN32 */ - #define GetFileDirectory(out) (GetConfigDirectory(out)) + #define GetFileDirectory(out) (GetConfigDirectory(out)) #endif /* WIN32 */ -#define INVALID_THREAD ((ThreadHandle)NULL) +#define INVALID_THREAD ((ThreadHandle)NULL) #ifndef MSG_NOSIGNAL -#define MSG_NOSIGNAL 0 +#define MSG_NOSIGNAL 0 #endif /* MSG_NOSIGNAL */ #ifndef MSG_MORE -#define MSG_MORE 0 +#define MSG_MORE 0 #endif /* MSG_MORE */ #ifndef MSG_WAITALL -#define MSG_WAITALL 0 +#define MSG_WAITALL 0 #endif /* MSG_WAITALL */ /* Unified interfaces end */ @@ -300,70 +300,70 @@ #define __STILL #ifdef HAVE_STDINT_H - #include + #include #else #ifndef HAVE_CONFIG_H - #ifndef __USE_MISC + #ifndef __USE_MISC - #if (INT_MAX == 2147483647) - #define int32_t int - #define uint32_t unsigned int - #define UINT32_T_MAX 0xFFFFFFFF - #endif + #if (INT_MAX == 2147483647) + #define int32_t int + #define uint32_t unsigned int + #define UINT32_T_MAX 0xFFFFFFFF + #endif - #if (SHRT_MAX == 32767) - #define int16_t short - #define uint16_t unsigned short - #endif + #if (SHRT_MAX == 32767) + #define int16_t short + #define uint16_t unsigned short + #endif - #endif + #endif #endif #endif #ifndef HAVE_IN_PORT_T - typedef uint16_t in_port_t; + typedef uint16_t in_port_t; #endif /* Parameters' tag */ #ifndef __in - #define __in + #define __in #endif /* __in */ #ifndef __in_opt - #define __in_opt + #define __in_opt #endif /* __in_opt */ #ifndef __out - #define __out + #define __out #endif /* __out */ #ifndef __out_opt - #define __out_opt + #define __out_opt #endif /* __out_opt */ #ifndef __inout - #define __inout + #define __inout #endif /* __inout */ #ifndef __inout_opt - #define __inout_opt + #define __inout_opt #endif /* __inout_opt */ -#define LENGTH_OF_IPV6_ADDRESS_ASCII (sizeof("XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:xxx.xxx.xxx.xxx")) -#define LENGTH_OF_IPV4_ADDRESS_ASCII (sizeof("xxx.xxx.xxx.xxx")) +#define LENGTH_OF_IPV6_ADDRESS_ASCII (sizeof("XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:xxx.xxx.xxx.xxx")) +#define LENGTH_OF_IPV4_ADDRESS_ASCII (sizeof("xxx.xxx.xxx.xxx")) typedef struct _Address_Type{ - /* Union of address of IPv4 and IPv6 */ - union { - struct sockaddr_in Addr4; - struct sockaddr_in6 Addr6; - } Addr; + /* Union of address of IPv4 and IPv6 */ + union { + struct sockaddr_in Addr4; + struct sockaddr_in6 Addr6; + } Addr; - /* Although there is a `family' field in both `struct sockaddr_in' and - * `struct sockaddr_in6', we also add it out here. - */ - sa_family_t family; + /* Although there is a `family' field in both `struct sockaddr_in' and + * `struct sockaddr_in6', we also add it out here. + */ + sa_family_t family; } Address_Type; diff --git a/dnscache.c b/dnscache.c index 6bae2434..3da4894d 100755 --- a/dnscache.c +++ b/dnscache.c @@ -11,47 +11,47 @@ #include "timedtask.h" #include "domainstatistic.h" -#define CACHE_VERSION 22 +#define CACHE_VERSION 22 -#define CACHE_END '\x0A' -#define CACHE_START '\xFF' +#define CACHE_END '\x0A' +#define CACHE_START '\xFF' -static BOOL Inited = FALSE; -static BOOL CacheParallel = FALSE; +static BOOL Inited = FALSE; +static BOOL CacheParallel = FALSE; -static RWLock CacheLock; +static RWLock CacheLock; -static FileHandle CacheFileHandle; -static MappingHandle CacheMappingHandle; -static char *MapStart; +static FileHandle CacheFileHandle; +static MappingHandle CacheMappingHandle; +static char *MapStart; -static int32_t CacheSize; -static BOOL IgnoreTTL; +static int32_t CacheSize; +static BOOL IgnoreTTL; -static int32_t *CacheCount; +static int32_t *CacheCount; -static volatile int32_t *CacheEnd; /* Offset */ +static volatile int32_t *CacheEnd; /* Offset */ -static CacheHT *CacheInfo; +static CacheHT *CacheInfo; -static CacheTtlCtrl *TtlCtrl = NULL; +static CacheTtlCtrl *TtlCtrl = NULL; struct _Header{ - uint32_t Ver; - int32_t CacheSize; - int32_t End; - int32_t CacheCount; - CacheHT ht; - char Comment[128 - sizeof(uint32_t) - sizeof(int32_t) - sizeof(int32_t) - sizeof(int32_t) - sizeof(CacheHT)]; + uint32_t Ver; + int32_t CacheSize; + int32_t End; + int32_t CacheCount; + CacheHT ht; + char Comment[128 - sizeof(uint32_t) - sizeof(int32_t) - sizeof(int32_t) - sizeof(int32_t) - sizeof(CacheHT)]; }; static void DNSCacheTTLCountdown_Task(void *Unused, void *Unused2) { - BOOL GotMutex = FALSE; + BOOL GotMutex = FALSE; - Array *ChunkList = &(CacheInfo->NodeChunk); - int loop = ChunkList->Used - 1; - Cht_Node *Node = (Cht_Node *)Array_GetBySubscript(ChunkList, loop); + Array *ChunkList = &(CacheInfo->NodeChunk); + int loop = ChunkList->Used - 1; + Cht_Node *Node = (Cht_Node *)Array_GetBySubscript(ChunkList, loop); time_t CurrentTime = time(NULL); @@ -97,217 +97,217 @@ static void DNSCacheTTLCountdown_Task(void *Unused, void *Unused2) static BOOL IsReloadable(void) { - struct _Header *Header = (struct _Header *)MapStart; + struct _Header *Header = (struct _Header *)MapStart; - if( Header->Ver != CACHE_VERSION ) - { - ERRORMSG("The existing cache is not compatible with this version of program.\n"); - return FALSE; - } + if( Header->Ver != CACHE_VERSION ) + { + ERRORMSG("The existing cache is not compatible with this version of program.\n"); + return FALSE; + } - if( Header->CacheSize != CacheSize ) - { - ERRORMSG("The size of the existing cache and the value of `CacheSize' should be equal.\n"); - return FALSE; - } + if( Header->CacheSize != CacheSize ) + { + ERRORMSG("The size of the existing cache and the value of `CacheSize' should be equal.\n"); + return FALSE; + } - return TRUE; + return TRUE; } static void ReloadCache(void) { - struct _Header *Header = (struct _Header *)MapStart; + struct _Header *Header = (struct _Header *)MapStart; - INFO("Reloading the cache ...\n"); + INFO("Reloading the cache ...\n"); - CacheInfo = &(Header->ht); + CacheInfo = &(Header->ht); - CacheHT_ReInit(CacheInfo, MapStart, CacheSize); + CacheHT_ReInit(CacheInfo, MapStart, CacheSize); - CacheEnd = &(Header->End); - CacheCount = &(Header->CacheCount); + CacheEnd = &(Header->End); + CacheCount = &(Header->CacheCount); - INFO("Cache reloaded, containing %d entries for %d items.\n", CacheInfo->NodeChunk.Used, (*CacheCount)); + INFO("Cache reloaded, containing %d entries for %d items.\n", CacheInfo->NodeChunk.Used, (*CacheCount)); } static void CreateNewCache(void) { - struct _Header *Header = (struct _Header *)MapStart; + struct _Header *Header = (struct _Header *)MapStart; - memset(MapStart, 0, CacheSize); + memset(MapStart, 0, CacheSize); - Header->Ver = CACHE_VERSION; - Header->CacheSize = CacheSize; - Header->CacheCount = 0; - CacheEnd = &(Header->End); - *CacheEnd = sizeof(struct _Header); - memset(Header->Comment, 0, sizeof(Header->Comment)); - strncpy(Header->Comment, + Header->Ver = CACHE_VERSION; + Header->CacheSize = CacheSize; + Header->CacheCount = 0; + CacheEnd = &(Header->End); + *CacheEnd = sizeof(struct _Header); + memset(Header->Comment, 0, sizeof(Header->Comment)); + strncpy(Header->Comment, "\nDo not edit this file.\n", sizeof(Header->Comment) ); Header->Comment[sizeof(Header->Comment) - 1] = '\0'; - CacheInfo = &(Header->ht); - CacheCount = &(Header->CacheCount); + CacheInfo = &(Header->ht); + CacheCount = &(Header->CacheCount); - CacheHT_Init(CacheInfo, MapStart, CacheSize); + CacheHT_Init(CacheInfo, MapStart, CacheSize); } static int InitCacheInfo(ConfigFileInfo *ConfigInfo, BOOL Reload) { - if( Reload == TRUE ) - { - if( IsReloadable() ) - { - ReloadCache(); - } else { - if( ConfigGetBoolean(ConfigInfo, "OverwriteCache") == FALSE ) - { - return -1; - } else { - CreateNewCache(); - INFO("The existing cache has been overwritten.\n"); - } - } - } else { - CreateNewCache(); - } - return 0; + if( Reload == TRUE ) + { + if( IsReloadable() ) + { + ReloadCache(); + } else { + if( ConfigGetBoolean(ConfigInfo, "OverwriteCache") == FALSE ) + { + return -1; + } else { + CreateNewCache(); + INFO("The existing cache has been overwritten.\n"); + } + } + } else { + CreateNewCache(); + } + return 0; } int DNSCache_Init(ConfigFileInfo *ConfigInfo) { - int _CacheSize = ConfigGetInt32(ConfigInfo, "CacheSize"); - const char *CacheFile = ConfigGetRawString(ConfigInfo, "CacheFile"); - int InitCacheInfoState; - - int OverrideTTL; - int TTLMultiple; - - StringList *ctc = ConfigGetStringList(ConfigInfo, "CacheControl"); - - if( ConfigGetBoolean(ConfigInfo, "UseCache") == FALSE ) - { - return 0; - } - - CacheParallel = ConfigGetBoolean(ConfigInfo, "CacheParallel"); - - IgnoreTTL = ConfigGetBoolean(ConfigInfo, "IgnoreTTL"); - - OverrideTTL = ConfigGetInt32(ConfigInfo, "OverrideTTL"); - TTLMultiple = ConfigGetInt32(ConfigInfo, "MultipleTTL"); - - if( ctc != NULL || OverrideTTL > -1 || TTLMultiple > 1 ) - { - TtlCtrl = malloc(sizeof(CacheTtlCtrl)); - if( TtlCtrl == NULL || CacheTtlCrtl_Init(TtlCtrl) != 0 ) - { - return -1; - } - } - - if( ctc != NULL ) - { - CacheTtlCrtl_Add_From_StringList(TtlCtrl, ctc); - } - - if( OverrideTTL > -1 ) - { - CacheTtlCrtl_Add(TtlCtrl, "*", TTL_STATE_FIXED, 1, OverrideTTL, TRUE); - } else { - if( TTLMultiple < 1 ) - { - ERRORMSG("Invalid `MultipleTTL'.\n"); - } else if( TTLMultiple > 1 ){ - CacheTtlCrtl_Add(TtlCtrl, "*", TTL_STATE_VARIABLE, TTLMultiple, 0, TRUE); - } - } + int _CacheSize = ConfigGetInt32(ConfigInfo, "CacheSize"); + const char *CacheFile = ConfigGetRawString(ConfigInfo, "CacheFile"); + int InitCacheInfoState; + + int OverrideTTL; + int TTLMultiple; + + StringList *ctc = ConfigGetStringList(ConfigInfo, "CacheControl"); + + if( ConfigGetBoolean(ConfigInfo, "UseCache") == FALSE ) + { + return 0; + } + + CacheParallel = ConfigGetBoolean(ConfigInfo, "CacheParallel"); + + IgnoreTTL = ConfigGetBoolean(ConfigInfo, "IgnoreTTL"); + + OverrideTTL = ConfigGetInt32(ConfigInfo, "OverrideTTL"); + TTLMultiple = ConfigGetInt32(ConfigInfo, "MultipleTTL"); + + if( ctc != NULL || OverrideTTL > -1 || TTLMultiple > 1 ) + { + TtlCtrl = malloc(sizeof(CacheTtlCtrl)); + if( TtlCtrl == NULL || CacheTtlCrtl_Init(TtlCtrl) != 0 ) + { + return -1; + } + } + + if( ctc != NULL ) + { + CacheTtlCrtl_Add_From_StringList(TtlCtrl, ctc); + } + + if( OverrideTTL > -1 ) + { + CacheTtlCrtl_Add(TtlCtrl, "*", TTL_STATE_FIXED, 1, OverrideTTL, TRUE); + } else { + if( TTLMultiple < 1 ) + { + ERRORMSG("Invalid `MultipleTTL'.\n"); + } else if( TTLMultiple > 1 ){ + CacheTtlCrtl_Add(TtlCtrl, "*", TTL_STATE_VARIABLE, TTLMultiple, 0, TRUE); + } + } CacheSize = ROUND_UP(_CacheSize, 8); - if( CacheSize < 102400 ) - { - ERRORMSG("Cache size must not less than 102400 bytes.\n"); - return 1; - } + if( CacheSize < 102400 ) + { + ERRORMSG("Cache size must not less than 102400 bytes.\n"); + return 1; + } - if( ConfigGetBoolean(ConfigInfo, "MemoryCache") == TRUE ) - { - MapStart = SafeMalloc(CacheSize); + if( ConfigGetBoolean(ConfigInfo, "MemoryCache") == TRUE ) + { + MapStart = SafeMalloc(CacheSize); - if( MapStart == NULL ) - { - ERRORMSG("Cache initializing failed.\n"); - return 2; - } + if( MapStart == NULL ) + { + ERRORMSG("Cache initializing failed.\n"); + return 2; + } - InitCacheInfoState = InitCacheInfo(ConfigInfo, FALSE); - } else { - BOOL FileExists; + InitCacheInfoState = InitCacheInfo(ConfigInfo, FALSE); + } else { + BOOL FileExists; - INFO("Cache File : %s\n", CacheFile); + INFO("Cache File : %s\n", CacheFile); - FileExists = FileIsReadable(CacheFile); + FileExists = FileIsReadable(CacheFile); - CacheFileHandle = OPEN_FILE(CacheFile); - if(CacheFileHandle == INVALID_FILE) - { - int ErrorNum = GET_LAST_ERROR(); - char ErrorMessage[320]; + CacheFileHandle = OPEN_FILE(CacheFile); + if(CacheFileHandle == INVALID_FILE) + { + int ErrorNum = GET_LAST_ERROR(); + char ErrorMessage[320]; - GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); + GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); - ERRORMSG("Cache initializing failed : %d : %s.\n", ErrorNum, ErrorMessage); + ERRORMSG("Cache initializing failed : %d : %s.\n", ErrorNum, ErrorMessage); - return 3; - } + return 3; + } - CacheMappingHandle = CREATE_FILE_MAPPING(CacheFileHandle, CacheSize); - if(CacheMappingHandle == INVALID_MAP) - { - int ErrorNum = GET_LAST_ERROR(); - char ErrorMessage[320]; + CacheMappingHandle = CREATE_FILE_MAPPING(CacheFileHandle, CacheSize); + if(CacheMappingHandle == INVALID_MAP) + { + int ErrorNum = GET_LAST_ERROR(); + char ErrorMessage[320]; - GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); + GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); - ERRORMSG("Cache initializing failed : %d : %s.\n", ErrorNum, ErrorMessage); - return 4; - } + ERRORMSG("Cache initializing failed : %d : %s.\n", ErrorNum, ErrorMessage); + return 4; + } - MapStart = (char *)MPA_FILE(CacheMappingHandle, CacheSize); - if(MapStart == INVALID_MAPPING_FILE) - { - int ErrorNum = GET_LAST_ERROR(); - char ErrorMessage[320]; + MapStart = (char *)MPA_FILE(CacheMappingHandle, CacheSize); + if(MapStart == INVALID_MAPPING_FILE) + { + int ErrorNum = GET_LAST_ERROR(); + char ErrorMessage[320]; - GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); + GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); - ERRORMSG("Cache initializing failed : %d : %s.\n", ErrorNum, ErrorMessage); - return 5; - } + ERRORMSG("Cache initializing failed : %d : %s.\n", ErrorNum, ErrorMessage); + return 5; + } - if( FileExists == FALSE ) - { - InitCacheInfoState = InitCacheInfo(ConfigInfo, FALSE); - } else { - InitCacheInfoState = InitCacheInfo(ConfigInfo, ConfigGetBoolean(ConfigInfo, "ReloadCache")); - } - } + if( FileExists == FALSE ) + { + InitCacheInfoState = InitCacheInfo(ConfigInfo, FALSE); + } else { + InitCacheInfoState = InitCacheInfo(ConfigInfo, ConfigGetBoolean(ConfigInfo, "ReloadCache")); + } + } - if( InitCacheInfoState != 0 ) - { - return 6; - } + if( InitCacheInfoState != 0 ) + { + return 6; + } - RWLock_Init(CacheLock); + RWLock_Init(CacheLock); - Inited = TRUE; + Inited = TRUE; - if( !IgnoreTTL ) + if( !IgnoreTTL ) { TimedTask_Add(TRUE, FALSE, @@ -319,88 +319,88 @@ int DNSCache_Init(ConfigFileInfo *ConfigInfo) ); } - return 0; + return 0; } BOOL Cache_IsInited(void) { - return Inited; + return Inited; } static int32_t DNSCache_GetAviliableChunk(uint32_t Length, Cht_Node **Out) { - int32_t NodeNumber; - Cht_Node *Node; - uint32_t RoundedLength = ROUND_UP(Length, 8); - - BOOL NewCreated; - - NodeNumber = CacheHT_FindUnusedNode(CacheInfo, RoundedLength, &Node, MapStart + (*CacheEnd) + RoundedLength, &NewCreated); - if( NodeNumber >= 0 ) - { - if( NewCreated == TRUE ) - { - Node->Offset = (*CacheEnd); - (*CacheEnd) += RoundedLength; - } - - memset(MapStart + Node->Offset + Length, 0xFE, RoundedLength - Length); - - *Out = Node; - return NodeNumber; - } else { - *Out = NULL; - return -1; - } + int32_t NodeNumber; + Cht_Node *Node; + uint32_t RoundedLength = ROUND_UP(Length, 8); + + BOOL NewCreated; + + NodeNumber = CacheHT_FindUnusedNode(CacheInfo, RoundedLength, &Node, MapStart + (*CacheEnd) + RoundedLength, &NewCreated); + if( NodeNumber >= 0 ) + { + if( NewCreated == TRUE ) + { + Node->Offset = (*CacheEnd); + (*CacheEnd) += RoundedLength; + } + + memset(MapStart + Node->Offset + Length, 0xFE, RoundedLength - Length); + + *Out = Node; + return NodeNumber; + } else { + *Out = NULL; + return -1; + } } static Cht_Node *DNSCache_FindFromCache(char *Content, size_t Length, Cht_Node *Start, time_t CurrentTime) { - Cht_Node *Node = Start; + Cht_Node *Node = Start; - do{ - Node = CacheHT_Get(CacheInfo, Content, Node, NULL); - if( Node == NULL ) - { - return NULL; - } + do{ + Node = CacheHT_Get(CacheInfo, Content, Node, NULL); + if( Node == NULL ) + { + return NULL; + } - if( IgnoreTTL == TRUE || (CurrentTime - Node->TimeAdded < Node->TTL) ) - { - if( memcmp(Content, MapStart + Node->Offset + 1, Length) == 0 ) - { - return Node; - } - } + if( IgnoreTTL == TRUE || (CurrentTime - Node->TimeAdded < Node->TTL) ) + { + if( memcmp(Content, MapStart + Node->Offset + 1, Length) == 0 ) + { + return Node; + } + } - } while( TRUE ); + } while( TRUE ); } static uint32_t DNSCache_CacheMinTTL(char *Content, size_t Length, uint32_t NewTTL, time_t CurrentTime) { - uint32_t RecordTTL = NewTTL; - Cht_Node *Node = NULL; - - /* Get the smallest, in case of not equal. */ - while( (Node = DNSCache_FindFromCache(Content, Length, Node, CurrentTime)) != NULL ) - { - uint32_t TTL = Node->TTL - (CurrentTime - Node->TimeAdded); - if( RecordTTL > TTL ) - { - RecordTTL = TTL; - } - } - - Node = NULL; - while( (Node = DNSCache_FindFromCache(Content, Length, Node, CurrentTime)) != NULL ) - { - Node->TTL = RecordTTL; - Node->TimeAdded = CurrentTime; - } - - return RecordTTL; + uint32_t RecordTTL = NewTTL; + Cht_Node *Node = NULL; + + /* Get the smallest, in case of not equal. */ + while( (Node = DNSCache_FindFromCache(Content, Length, Node, CurrentTime)) != NULL ) + { + uint32_t TTL = Node->TTL - (CurrentTime - Node->TimeAdded); + if( RecordTTL > TTL ) + { + RecordTTL = TTL; + } + } + + Node = NULL; + while( (Node = DNSCache_FindFromCache(Content, Length, Node, CurrentTime)) != NULL ) + { + Node->TTL = RecordTTL; + Node->TimeAdded = CurrentTime; + } + + return RecordTTL; } /* Item: \xFFStrName\x01IntType\x01IntClass\x00ParsedAnswer\x0A @@ -411,59 +411,59 @@ static int DNSCache_AddAItemToCache(DnsSimpleParserIterator *i, const CtrlContent *InfectedTtlContent ) { - /* used to store cache data temporarily, TODO: no bounds checking here */ - char Buffer[512]; - char *Item = Buffer + 1; - - /* Iterator of `Buffer' */ - char *BufferItr = Buffer; - - const CtrlContent *TtlContent; - - /* Assign start byte of the cache */ - Buffer[0] = CACHE_START; - - /* Assign the name of the cache */ - if( i->GetName(i, Item, sizeof(Buffer) -1) < 0 ) - { - return -1; - } - - /* Detemine which TTL scheme will be used */ - if( InfectedTtlContent != NULL ) - { - switch( InfectedTtlContent->Infection ) - { - default: - case TTL_CTRL_INFECTION_AGGRESSIVLY: - TtlContent = InfectedTtlContent; - break; - - case TTL_CTRL_INFECTION_PASSIVLY: - TtlContent = CacheTtlCrtl_Get(TtlCtrl, Item); - if( TtlContent == NULL ) - { - TtlContent = InfectedTtlContent; - } - break; - - case TTL_CTRL_INFECTION_NONE: - TtlContent = CacheTtlCrtl_Get(TtlCtrl, Item); - break; - } - } else { - TtlContent = CacheTtlCrtl_Get(TtlCtrl, Item); - } - - /* Jump just over the name, right at '\0' */ - BufferItr = Item + strlen(Item); + /* used to store cache data temporarily, TODO: no bounds checking here */ + char Buffer[512]; + char *Item = Buffer + 1; + + /* Iterator of `Buffer' */ + char *BufferItr = Buffer; + + const CtrlContent *TtlContent; + + /* Assign start byte of the cache */ + Buffer[0] = CACHE_START; + + /* Assign the name of the cache */ + if( i->GetName(i, Item, sizeof(Buffer) -1) < 0 ) + { + return -1; + } + + /* Detemine which TTL scheme will be used */ + if( InfectedTtlContent != NULL ) + { + switch( InfectedTtlContent->Infection ) + { + default: + case TTL_CTRL_INFECTION_AGGRESSIVLY: + TtlContent = InfectedTtlContent; + break; + + case TTL_CTRL_INFECTION_PASSIVLY: + TtlContent = CacheTtlCrtl_Get(TtlCtrl, Item); + if( TtlContent == NULL ) + { + TtlContent = InfectedTtlContent; + } + break; + + case TTL_CTRL_INFECTION_NONE: + TtlContent = CacheTtlCrtl_Get(TtlCtrl, Item); + break; + } + } else { + TtlContent = CacheTtlCrtl_Get(TtlCtrl, Item); + } + + /* Jump just over the name, right at '\0' */ + BufferItr = Item + strlen(Item); if( BufferItr >= Buffer + sizeof(Buffer) ) { return -2; } - /* Set record type and class */ - BufferItr += snprintf(BufferItr, + /* Set record type and class */ + BufferItr += snprintf(BufferItr, sizeof(Buffer) - (BufferItr - Buffer), "\1%d\1%d", i->Type, @@ -474,14 +474,14 @@ static int DNSCache_AddAItemToCache(DnsSimpleParserIterator *i, return -3; } - /* End of name\1type\1class triple */ - *BufferItr++ = '\0'; + /* End of name\1type\1class triple */ + *BufferItr++ = '\0'; if( BufferItr >= Buffer + sizeof(Buffer) ) { return -4; } - /* Generate data and store them */ + /* Generate data and store them */ if( i->TextifyData(i, "%v", BufferItr, @@ -490,111 +490,111 @@ static int DNSCache_AddAItemToCache(DnsSimpleParserIterator *i, { return -5; } - BufferItr += strlen(BufferItr) + 1; + BufferItr += strlen(BufferItr) + 1; if( BufferItr >= Buffer + sizeof(Buffer) ) { return -6; } - /* Mark the end */ - *BufferItr = CACHE_END; + /* Mark the end */ + *BufferItr = CACHE_END; - /* The whole cache data generating completed */ + /* The whole cache data generating completed */ - /* Add the cache item to the main cache zone below */ + /* Add the cache item to the main cache zone below */ - /* Determine whether the cache item has existed in the main cache zone */ - if(DNSCache_FindFromCache(Item, BufferItr - Buffer, NULL, CurrentTime) == NULL) - { - /* If not, add it */ + /* Determine whether the cache item has existed in the main cache zone */ + if(DNSCache_FindFromCache(Item, BufferItr - Buffer, NULL, CurrentTime) == NULL) + { + /* If not, add it */ - /* Subscript of a chunk in the main cache zone */ - int32_t Subscript; + /* Subscript of a chunk in the main cache zone */ + int32_t Subscript; - uint32_t RecordTTL; + uint32_t RecordTTL; - /* Node with subscript `Subscript' */ - Cht_Node *Node; + /* Node with subscript `Subscript' */ + Cht_Node *Node; - if( TtlContent != NULL ) - { - switch( TtlContent->State ) - { - case TTL_STATE_NO_CACHE: - RecordTTL = 0; - break; + if( TtlContent != NULL ) + { + switch( TtlContent->State ) + { + case TTL_STATE_NO_CACHE: + RecordTTL = 0; + break; - case TTL_STATE_ORIGINAL: - RecordTTL = i->GetTTL(i); - break; + case TTL_STATE_ORIGINAL: + RecordTTL = i->GetTTL(i); + break; - default: - RecordTTL = (TtlContent->Coefficient) * i->GetTTL(i) + (TtlContent->Increment); - break; - } - } else { - RecordTTL = i->GetTTL(i); - } + default: + RecordTTL = (TtlContent->Coefficient) * i->GetTTL(i) + (TtlContent->Increment); + break; + } + } else { + RecordTTL = i->GetTTL(i); + } - if( RecordTTL == 0 ) - { - return 0; - } + if( RecordTTL == 0 ) + { + return 0; + } - /* Get a usable chunk and its subscript */ - Subscript = DNSCache_GetAviliableChunk(BufferItr - Buffer + 1, &Node); + /* Get a usable chunk and its subscript */ + Subscript = DNSCache_GetAviliableChunk(BufferItr - Buffer + 1, &Node); - /* If there is a usable chunk */ - if(Subscript >= 0) - { - /* Copy the cache to this entry */ - memcpy(MapStart + Node->Offset, Buffer, BufferItr - Buffer + 1); + /* If there is a usable chunk */ + if(Subscript >= 0) + { + /* Copy the cache to this entry */ + memcpy(MapStart + Node->Offset, Buffer, BufferItr - Buffer + 1); - if( CacheParallel ) - { - RecordTTL = DNSCache_CacheMinTTL(Item, strlen(Item), RecordTTL, CurrentTime); - } + if( CacheParallel ) + { + RecordTTL = DNSCache_CacheMinTTL(Item, strlen(Item), RecordTTL, CurrentTime); + } - /* Assign TTL */ - Node->TTL = RecordTTL; + /* Assign TTL */ + Node->TTL = RecordTTL; - Node->TimeAdded = CurrentTime; + Node->TimeAdded = CurrentTime; - /* Index this entry on the hash table */ - CacheHT_InsertToSlot(CacheInfo, Item, Subscript, Node, NULL); + /* Index this entry on the hash table */ + CacheHT_InsertToSlot(CacheInfo, Item, Subscript, Node, NULL); - ++(*CacheCount); - } else { - return -1; - } - } + ++(*CacheCount); + } else { + return -1; + } + } - return 0; + return 0; } int DNSCache_AddItemsToCache(IHeader *Header, BOOL IsFirst) { char *DnsEntity = IHEADER_TAIL(Header); - const CtrlContent *TtlContent = NULL; + const CtrlContent *TtlContent = NULL; - DnsSimpleParser p; - DnsSimpleParserIterator i; + DnsSimpleParser p; + DnsSimpleParserIterator i; - if(Inited == FALSE) return 0; - if(!IsFirst && !CacheParallel) return 0; + if(Inited == FALSE) return 0; + if(!IsFirst && !CacheParallel) return 0; - if( DnsSimpleParser_Init(&p, DnsEntity, Header->EntityLength, FALSE) != 0 ) + if( DnsSimpleParser_Init(&p, DnsEntity, Header->EntityLength, FALSE) != 0 ) { return -1; } - if( DnsSimpleParserIterator_Init(&i, &p) != 0 ) + if( DnsSimpleParserIterator_Init(&i, &p) != 0 ) { return -2; } - TtlContent = CacheTtlCrtl_Get(TtlCtrl, Header->Domain); - RWLock_WrLock(CacheLock); + TtlContent = CacheTtlCrtl_Get(TtlCtrl, Header->Domain); + RWLock_WrLock(CacheLock); while( i.Next(&i) != NULL ) { @@ -613,24 +613,24 @@ int DNSCache_AddItemsToCache(IHeader *Header, BOOL IsFirst) } } - RWLock_UnWLock(CacheLock); + RWLock_UnWLock(CacheLock); - return 0; + return 0; } /* State code returned */ -static int DNSCache_GetRawRecordsFromCache( __in const char *Name, +static int DNSCache_GetRawRecordsFromCache( __in const char *Name, __in DNSRecordType Type, __in DNSRecordClass Klass, __inout DnsGenerator *g, - __in time_t CurrentTime - ) + __in time_t CurrentTime + ) { - int Ret = -100; + int Ret = -100; - char Name_Type_Class[256]; + char Name_Type_Class[256]; - uint32_t NewTTL; + uint32_t NewTTL; Cht_Node *Node = NULL; /* Important */ @@ -646,26 +646,26 @@ static int DNSCache_GetRawRecordsFromCache( __in const char *Name, return -609; } - do - { + do + { char *CacheItr; - Node = DNSCache_FindFromCache(Name_Type_Class, + Node = DNSCache_FindFromCache(Name_Type_Class, strlen(Name_Type_Class) + 1, Node, CurrentTime ); - if( Node == NULL ) - { - break; - } + if( Node == NULL ) + { + break; + } - Ret = 0; + Ret = 0; - if( Node->TTL != 0 ) - { - /* TTL*/ + if( Node->TTL != 0 ) + { + /* TTL*/ if( IgnoreTTL == TRUE ) { NewTTL = Node->TTL; @@ -709,33 +709,33 @@ static int DNSCache_GetRawRecordsFromCache( __in const char *Name, return -4; break; } - } - } while ( TRUE ); + } + } while ( TRUE ); return Ret; } static Cht_Node *DNSCache_GetCNameFromCache(__in char *Name, __out char *Buffer, __in time_t CurrentTime) { - char Name_Type_Class[256]; - Cht_Node *Node = NULL; + char Name_Type_Class[256]; + Cht_Node *Node = NULL; - if( snprintf(Name_Type_Class, sizeof(Name_Type_Class), "%s\1%d\1%d", Name, DNS_TYPE_CNAME, 1) >= sizeof(Name_Type_Class) ){ + if( snprintf(Name_Type_Class, sizeof(Name_Type_Class), "%s\1%d\1%d", Name, DNS_TYPE_CNAME, 1) >= sizeof(Name_Type_Class) ){ return NULL; } - do - { - Node = DNSCache_FindFromCache(Name_Type_Class, strlen(Name_Type_Class) + 1, Node, CurrentTime); - if( Node == NULL ) - { - return NULL; - } + do + { + Node = DNSCache_FindFromCache(Name_Type_Class, strlen(Name_Type_Class) + 1, Node, CurrentTime); + if( Node == NULL ) + { + return NULL; + } - strcpy(Buffer, MapStart + Node->Offset + 1 + strlen(Name_Type_Class) + 1); - return Node; + strcpy(Buffer, MapStart + Node->Offset + 1 + strlen(Name_Type_Class) + 1); + return Node; - } while( TRUE ); + } while( TRUE ); } @@ -745,19 +745,19 @@ static int DNSCache_GetByQuestion(__inout DnsGenerator *g, __in time_t CurrentTime ) { - char Name[260]; - char CName[260]; + char Name[260]; + char CName[260]; uint32_t NewTTL; - DnsSimpleParserIterator i; + DnsSimpleParserIterator i; - if( DnsSimpleParserIterator_Init(&i, p) != 0 ) + if( DnsSimpleParserIterator_Init(&i, p) != 0 ) { return -1; } - if( i.Next(&i) == NULL || i.Purpose != DNS_RECORD_PURPOSE_QUESTION ) + if( i.Next(&i) == NULL || i.Purpose != DNS_RECORD_PURPOSE_QUESTION ) { return -2; } @@ -779,20 +779,20 @@ static int DNSCache_GetByQuestion(__inout DnsGenerator *g, RWLock_RdLock(CacheLock); - /* If the intended type is not DNS_TYPE_CNAME, then first find its cname */ - if( i.Type != DNS_TYPE_CNAME ) + /* If the intended type is not DNS_TYPE_CNAME, then first find its cname */ + if( i.Type != DNS_TYPE_CNAME ) { Cht_Node *Node = NULL; - while( (Node = DNSCache_GetCNameFromCache(Name, CName, CurrentTime)) + while( (Node = DNSCache_GetCNameFromCache(Name, CName, CurrentTime)) != NULL ) - { - if( IgnoreTTL == TRUE ) - { - NewTTL = Node->TTL; - } else { - NewTTL = Node->TTL - (CurrentTime - Node->TimeAdded); - } + { + if( IgnoreTTL == TRUE ) + { + NewTTL = Node->TTL; + } else { + NewTTL = Node->TTL - (CurrentTime - Node->TimeAdded); + } if( g->CName(g, "a", CName, NewTTL) != 0 ) { @@ -800,8 +800,8 @@ static int DNSCache_GetByQuestion(__inout DnsGenerator *g, return -5; } - strcpy(Name, CName); - } + strcpy(Name, CName); + } } if( DNSCache_GetRawRecordsFromCache(Name, i.Type, i.Klass, g, CurrentTime) @@ -829,10 +829,10 @@ int DNSCache_FetchFromCache(IHeader *h /* Entity followed */, int BufferLength) int ResultLength; - if( Inited != TRUE ) - { - return -792; - } + if( Inited != TRUE ) + { + return -792; + } /* We did/do NOT cache these types of answers. EDNS0: https://datatracker.ietf.org/doc/html/rfc2671 diff --git a/dnsgenerator.c b/dnsgenerator.c index 1215b7cc..b9927743 100755 --- a/dnsgenerator.c +++ b/dnsgenerator.c @@ -5,29 +5,29 @@ /* Other Codes */ char *DNSLabelizedName(__inout char *Origin, __in size_t OriginSpaceLength){ - unsigned char *LabelLength = (unsigned char *)Origin; + unsigned char *LabelLength = (unsigned char *)Origin; - if( *Origin == '\0' ) - return Origin + 1; + if( *Origin == '\0' ) + return Origin + 1; - if( OriginSpaceLength < strlen(Origin) + 2 ) - return NULL; + if( OriginSpaceLength < strlen(Origin) + 2 ) + return NULL; - memmove(Origin + 1, Origin, strlen(Origin) + 1); + memmove(Origin + 1, Origin, strlen(Origin) + 1); - *LabelLength = 0; - while(1){ - ++Origin; + *LabelLength = 0; + while(1){ + ++Origin; - if(*Origin == 0) break; - if(*Origin != '.') ++(*LabelLength); - else { - LabelLength = (unsigned char *)Origin; - *LabelLength = 0; - } - } + if(*Origin == 0) break; + if(*Origin != '.') ++(*LabelLength); + else { + LabelLength = (unsigned char *)Origin; + *LabelLength = 0; + } + } - return Origin + 1; + return Origin + 1; } /* Compressed length returned */ @@ -144,7 +144,7 @@ static DnsRecordPurpose DnsGenerator_NextPurpose(DnsGenerator *g) static int DnsGenerator_NamePart(DnsGenerator *g, const char *Name) { - if( Name == NULL || *Name == '\0' ) + if( Name == NULL || *Name == '\0' ) { /* Root domain */ if( LEFT_LENGTH(g) < 1 ) @@ -179,7 +179,7 @@ static int DnsGenerator_NamePart(DnsGenerator *g, const char *Name) static int DnsGenerator_16Uint(DnsGenerator *g, int Value) { - if( LEFT_LENGTH(g) < 2 ) + if( LEFT_LENGTH(g) < 2 ) { return -1; } @@ -193,7 +193,7 @@ static int DnsGenerator_16Uint(DnsGenerator *g, int Value) static int DnsGenerator_32Uint(DnsGenerator *g, int Value) { - if( LEFT_LENGTH(g) < 4 ) + if( LEFT_LENGTH(g) < 4 ) { return -1; } @@ -207,7 +207,7 @@ static int DnsGenerator_32Uint(DnsGenerator *g, int Value) static int DnsGenerator_IPv4(DnsGenerator *g, const char *ip) { - if( LEFT_LENGTH(g) < 4 ) + if( LEFT_LENGTH(g) < 4 ) { return -1; } @@ -221,7 +221,7 @@ static int DnsGenerator_IPv4(DnsGenerator *g, const char *ip) static int DnsGenerator_IPv6(DnsGenerator *g, const char *ip) { - if( LEFT_LENGTH(g) < 16 ) + if( LEFT_LENGTH(g) < 16 ) { return -1; } @@ -245,17 +245,17 @@ static int DnsGenerator_Question(DnsGenerator *g, return 1; } - if( DnsGenerator_NamePart(g, Name) != 0 ) + if( DnsGenerator_NamePart(g, Name) != 0 ) { return -1; } - if( DnsGenerator_16Uint(g, Type) != 0 ) + if( DnsGenerator_16Uint(g, Type) != 0 ) { return -2; } - if( DnsGenerator_16Uint(g, Klass) != 0 ) + if( DnsGenerator_16Uint(g, Klass) != 0 ) { return -3; } @@ -264,7 +264,7 @@ static int DnsGenerator_Question(DnsGenerator *g, GET_16_BIT_U_INT(g->NumberOfRecords) + 1 ); - return 0; + return 0; } static int DnsGenerator_CName(DnsGenerator *g, @@ -283,32 +283,32 @@ static int DnsGenerator_CName(DnsGenerator *g, return 1; } - if( DnsGenerator_NamePart(g, Name) != 0 ) + if( DnsGenerator_NamePart(g, Name) != 0 ) { return -1; } - if( DnsGenerator_16Uint(g, DNS_TYPE_CNAME) != 0 ) + if( DnsGenerator_16Uint(g, DNS_TYPE_CNAME) != 0 ) { return -2; } - if( DnsGenerator_16Uint(g, DNS_CLASS_IN) != 0 ) + if( DnsGenerator_16Uint(g, DNS_CLASS_IN) != 0 ) { return -3; } - if( DnsGenerator_32Uint(g, Ttl) != 0 ) + if( DnsGenerator_32Uint(g, Ttl) != 0 ) { return -4; } - if( DnsGenerator_16Uint(g, LABEL_LENGTH(CName)) != 0 ) + if( DnsGenerator_16Uint(g, LABEL_LENGTH(CName)) != 0 ) { return -5; } - if( DnsGenerator_NamePart(g, CName) != 0 ) + if( DnsGenerator_NamePart(g, CName) != 0 ) { return -6; } @@ -336,32 +336,32 @@ static int DnsGenerator_A(DnsGenerator *g, return 1; } - if( DnsGenerator_NamePart(g, Name) != 0 ) + if( DnsGenerator_NamePart(g, Name) != 0 ) { return -1; } - if( DnsGenerator_16Uint(g, DNS_TYPE_A) != 0 ) + if( DnsGenerator_16Uint(g, DNS_TYPE_A) != 0 ) { return -2; } - if( DnsGenerator_16Uint(g, DNS_CLASS_IN) != 0 ) + if( DnsGenerator_16Uint(g, DNS_CLASS_IN) != 0 ) { return -3; } - if( DnsGenerator_32Uint(g, Ttl) != 0 ) + if( DnsGenerator_32Uint(g, Ttl) != 0 ) { return -4; } - if( DnsGenerator_16Uint(g, 4) != 0 ) + if( DnsGenerator_16Uint(g, 4) != 0 ) { return -5; } - if( DnsGenerator_IPv4(g, ip) != 0 ) + if( DnsGenerator_IPv4(g, ip) != 0 ) { return -6; } @@ -389,32 +389,32 @@ static int DnsGenerator_AAAA(DnsGenerator *g, return 1; } - if( DnsGenerator_NamePart(g, Name) != 0 ) + if( DnsGenerator_NamePart(g, Name) != 0 ) { return -1; } - if( DnsGenerator_16Uint(g, DNS_TYPE_AAAA) != 0 ) + if( DnsGenerator_16Uint(g, DNS_TYPE_AAAA) != 0 ) { return -2; } - if( DnsGenerator_16Uint(g, DNS_CLASS_IN) != 0 ) + if( DnsGenerator_16Uint(g, DNS_CLASS_IN) != 0 ) { return -3; } - if( DnsGenerator_32Uint(g, Ttl) != 0 ) + if( DnsGenerator_32Uint(g, Ttl) != 0 ) { return -4; } - if( DnsGenerator_16Uint(g, 16) != 0 ) + if( DnsGenerator_16Uint(g, 16) != 0 ) { return -5; } - if( DnsGenerator_IPv6(g, ip) != 0 ) + if( DnsGenerator_IPv6(g, ip) != 0 ) { return -6; } @@ -435,27 +435,27 @@ static int DnsGenerator_EDns(DnsGenerator *g, int UdpPayloadSize) return 1; } - if( DnsGenerator_NamePart(g, NULL) != 0 ) + if( DnsGenerator_NamePart(g, NULL) != 0 ) { return -1; } - if( DnsGenerator_16Uint(g, DNS_TYPE_OPT) != 0 ) + if( DnsGenerator_16Uint(g, DNS_TYPE_OPT) != 0 ) { return -2; } - if( DnsGenerator_16Uint(g, UdpPayloadSize) != 0 ) + if( DnsGenerator_16Uint(g, UdpPayloadSize) != 0 ) { return -3; } - if( DnsGenerator_32Uint(g, 0) != 0 ) + if( DnsGenerator_32Uint(g, 0) != 0 ) { return -4; } - if( DnsGenerator_16Uint(g, 0) != 0 ) + if( DnsGenerator_16Uint(g, 0) != 0 ) { return -5; } @@ -491,27 +491,27 @@ static int DnsGenerator_RawData(DnsGenerator *g, return 2; } - if( DnsGenerator_NamePart(g, Name) != 0 ) + if( DnsGenerator_NamePart(g, Name) != 0 ) { return -1; } - if( DnsGenerator_16Uint(g, Type) != 0 ) + if( DnsGenerator_16Uint(g, Type) != 0 ) { return -2; } - if( DnsGenerator_16Uint(g, Klass) != 0 ) + if( DnsGenerator_16Uint(g, Klass) != 0 ) { return -3; } - if( DnsGenerator_32Uint(g, Ttl) != 0 ) + if( DnsGenerator_32Uint(g, Ttl) != 0 ) { return -4; } - if( DnsGenerator_16Uint(g, DataLength) != 0 ) + if( DnsGenerator_16Uint(g, DataLength) != 0 ) { return -5; } diff --git a/dnsgenerator.h b/dnsgenerator.h index 0d521eaa..548e1ea6 100755 --- a/dnsgenerator.h +++ b/dnsgenerator.h @@ -7,23 +7,23 @@ #include "stringlist.h" #include "common.h" -#define SET_16_BIT_U_INT(here, val) (*(uint16_t *)(here) = htons((uint16_t)(val))) -#define SET_32_BIT_U_INT(here, val) (*(uint32_t *)(here) = htonl((uint32_t)(val))) +#define SET_16_BIT_U_INT(here, val) (*(uint16_t *)(here) = htons((uint16_t)(val))) +#define SET_32_BIT_U_INT(here, val) (*(uint32_t *)(here) = htonl((uint32_t)(val))) /* Handle DNS header*/ -#define DNSSetQueryIdentifier(dns_start, QId) SET_16_BIT_U_INT((char *)(dns_start), QId) +#define DNSSetQueryIdentifier(dns_start, QId) SET_16_BIT_U_INT((char *)(dns_start), QId) -#define DNSSetFlags(dns_start, Flags) SET_16_BIT_U_INT((char *)(dns_start) + 2, Flags) +#define DNSSetFlags(dns_start, Flags) SET_16_BIT_U_INT((char *)(dns_start) + 2, Flags) -#define DNSSetQuestionCount(dns_start, QC) SET_16_BIT_U_INT((char *)(dns_start) + 4, QC) +#define DNSSetQuestionCount(dns_start, QC) SET_16_BIT_U_INT((char *)(dns_start) + 4, QC) -#define DNSSetAnswerCount(dns_start, AnC) SET_16_BIT_U_INT((char *)(dns_start) + 6, AnC) +#define DNSSetAnswerCount(dns_start, AnC) SET_16_BIT_U_INT((char *)(dns_start) + 6, AnC) -#define DNSSetNameServerCount(dns_start, ASC) SET_16_BIT_U_INT((char *)(dns_start) + 8, ASC) +#define DNSSetNameServerCount(dns_start, ASC) SET_16_BIT_U_INT((char *)(dns_start) + 8, ASC) -#define DNSSetAdditionalCount(dns_start, AdC) SET_16_BIT_U_INT((char *)(dns_start) + 10, AdC) +#define DNSSetAdditionalCount(dns_start, AdC) SET_16_BIT_U_INT((char *)(dns_start) + 10, AdC) -#define DNSLabelMakePointer(pointer_ptr, location) (((unsigned char *)(pointer_ptr))[0] = (192 + (location) / 256), ((unsigned char *)(pointer_ptr))[1] = (location) % 256) +#define DNSLabelMakePointer(pointer_ptr, location) (((unsigned char *)(pointer_ptr))[0] = (192 + (location) / 256), ((unsigned char *)(pointer_ptr))[1] = (location) % 256) char *DNSLabelizedName(__inout char *Origin, __in size_t OriginSpaceLength); diff --git a/dnsparser.c b/dnsparser.c index bb7a2c7a..124a2b60 100755 --- a/dnsparser.c +++ b/dnsparser.c @@ -4,141 +4,141 @@ char *DNSJumpOverName(char *NameStart) { - return NameStart + DNSGetHostName(NULL, INT_MAX, NameStart, NULL, 0); + return NameStart + DNSGetHostName(NULL, INT_MAX, NameStart, NULL, 0); } /* Labels length returned */ int DNSGetHostName(const char *DNSBody, int DNSBodyLength, const char *NameStart, char *buffer, int BufferLength) { - char *BufferItr = buffer; - const char *NameItr = NameStart; - int LabelsLength = 0; - BOOL Redirected = FALSE; - int LabelCount = GET_8_BIT_U_INT(NameItr); /* The amount of characters of the next label */ - while( LabelCount != 0 ) - { - if( DNSIsLabelPointerStart(LabelCount) ) - { - int LabelPointer = 0; - if( Redirected == FALSE ) + char *BufferItr = buffer; + const char *NameItr = NameStart; + int LabelsLength = 0; + BOOL Redirected = FALSE; + int LabelCount = GET_8_BIT_U_INT(NameItr); /* The amount of characters of the next label */ + while( LabelCount != 0 ) + { + if( DNSIsLabelPointerStart(LabelCount) ) + { + int LabelPointer = 0; + if( Redirected == FALSE ) { LabelsLength += 2; Redirected = TRUE; } - if( buffer == NULL ) - { - break; - } - LabelPointer = DNSLabelGetPointer(NameItr); - if( LabelPointer > DNSBodyLength ) - { - return -1; - } - NameItr = DNSBody + DNSLabelGetPointer(NameItr); - } else { - if( DNSBody != NULL && + if( buffer == NULL ) + { + break; + } + LabelPointer = DNSLabelGetPointer(NameItr); + if( LabelPointer > DNSBodyLength ) + { + return -1; + } + NameItr = DNSBody + DNSLabelGetPointer(NameItr); + } else { + if( DNSBody != NULL && NameItr + LabelCount > DNSBody + DNSBodyLength ) - { - return -1; - } - - if( buffer != NULL ) - { - if( BufferItr + LabelCount + 1 - buffer <= BufferLength ) - { - memcpy(BufferItr, NameItr + 1, LabelCount); - } else { - if( BufferItr == buffer ) - { - if( BufferLength > 0 ) - { - *BufferItr = '\0'; - } - } else { - *(BufferItr - 1) = '\0'; - } - return -1; - } - } - - if( Redirected == FALSE ) - { - LabelsLength += (LabelCount + 1); - } - NameItr += (1 + LabelCount); - if( buffer != NULL ) - { - BufferItr += LabelCount; - *BufferItr = '.'; - ++BufferItr; - } - } - - LabelCount = GET_8_BIT_U_INT(NameItr); - } - - if( buffer != NULL ) - { - if( BufferItr == buffer ) - { - if( BufferLength > 0 ) - { - *BufferItr = '\0'; - } else { - return -1; - } - } else { - *(BufferItr - 1) = '\0'; - } - } - - if( Redirected == FALSE ) - { - ++LabelsLength; - } - - return LabelsLength; + { + return -1; + } + + if( buffer != NULL ) + { + if( BufferItr + LabelCount + 1 - buffer <= BufferLength ) + { + memcpy(BufferItr, NameItr + 1, LabelCount); + } else { + if( BufferItr == buffer ) + { + if( BufferLength > 0 ) + { + *BufferItr = '\0'; + } + } else { + *(BufferItr - 1) = '\0'; + } + return -1; + } + } + + if( Redirected == FALSE ) + { + LabelsLength += (LabelCount + 1); + } + NameItr += (1 + LabelCount); + if( buffer != NULL ) + { + BufferItr += LabelCount; + *BufferItr = '.'; + ++BufferItr; + } + } + + LabelCount = GET_8_BIT_U_INT(NameItr); + } + + if( buffer != NULL ) + { + if( BufferItr == buffer ) + { + if( BufferLength > 0 ) + { + *BufferItr = '\0'; + } else { + return -1; + } + } else { + *(BufferItr - 1) = '\0'; + } + } + + if( Redirected == FALSE ) + { + ++LabelsLength; + } + + return LabelsLength; } /* including terminated-zero */ int DNSGetHostNameLength(const char *DNSBody, int DNSBodyLength, const char *NameStart) { - const char *NameItr = NameStart; - int NameLength = 0; - int LabelCount = GET_8_BIT_U_INT(NameItr); /* The amount of characters of the next label */ - while( LabelCount != 0 ) - { - if( DNSIsLabelPointerStart(LabelCount) ) - { - if( DNSLabelGetPointer(NameItr) > DNSBodyLength ) - { - return INT_MAX; /* Error detected */ - } - NameItr = DNSBody + DNSLabelGetPointer(NameItr); - } else { - if( NameItr + LabelCount > DNSBody + DNSBodyLength ) - { - return INT_MAX; /* Error detected */ - } - NameLength += (LabelCount + 1); - NameItr += (1 + LabelCount); - } - - LabelCount = GET_8_BIT_U_INT(NameItr); - - if( NameLength > DNSBodyLength ) + const char *NameItr = NameStart; + int NameLength = 0; + int LabelCount = GET_8_BIT_U_INT(NameItr); /* The amount of characters of the next label */ + while( LabelCount != 0 ) + { + if( DNSIsLabelPointerStart(LabelCount) ) + { + if( DNSLabelGetPointer(NameItr) > DNSBodyLength ) + { + return INT_MAX; /* Error detected */ + } + NameItr = DNSBody + DNSLabelGetPointer(NameItr); + } else { + if( NameItr + LabelCount > DNSBody + DNSBodyLength ) + { + return INT_MAX; /* Error detected */ + } + NameLength += (LabelCount + 1); + NameItr += (1 + LabelCount); + } + + LabelCount = GET_8_BIT_U_INT(NameItr); + + if( NameLength > DNSBodyLength ) { return INT_MAX; /* Error detected */ } - } - - if( NameLength == 0 ) - { - return 1; - } else { - return NameLength; - } + } + + if( NameLength == 0 ) + { + return 1; + } else { + return NameLength; + } } char *GetAllAnswers(char *DNSBody, int DNSBodyLength, char *Buffer, int BufferLength) @@ -203,30 +203,30 @@ int DNSCopyLable(const char *DNSBody, char *here, const char *src) { int FullLength = 0; - while( TRUE ) - { - if( DNSIsLabelPointerStart(GET_8_BIT_U_INT(src)) ) - { - src = DNSBody + DNSLabelGetPointer(src); - } else { - ++FullLength; + while( TRUE ) + { + if( DNSIsLabelPointerStart(GET_8_BIT_U_INT(src)) ) + { + src = DNSBody + DNSLabelGetPointer(src); + } else { + ++FullLength; - if( here != NULL ) + if( here != NULL ) { *here = *src; ++here; } - if( *src == '\0' ) - { - break; - } + if( *src == '\0' ) + { + break; + } - ++src; - } - } + ++src; + } + } - return FullLength; + return FullLength; } /** diff --git a/dnsparser.h b/dnsparser.h index 31462e44..6df908f8 100755 --- a/dnsparser.h +++ b/dnsparser.h @@ -5,34 +5,34 @@ #include "common.h" #include "dnsrelated.h" -#define GET_16_BIT_U_INT(ptr) (ntohs(*(int16_t *)(ptr))) -#define GET_32_BIT_U_INT(ptr) (ntohl(*(int32_t *)(ptr))) -#define GET_8_BIT_U_INT(ptr) (*(unsigned char*)(ptr)) +#define GET_16_BIT_U_INT(ptr) (ntohs(*(int16_t *)(ptr))) +#define GET_32_BIT_U_INT(ptr) (ntohl(*(int32_t *)(ptr))) +#define GET_8_BIT_U_INT(ptr) (*(unsigned char*)(ptr)) -#define DNS_HEADER_LENGTH 12 +#define DNS_HEADER_LENGTH 12 /* Handle DNS header*/ -#define DNSGetTCPLength(dns_over_tcp_ptr) GET_16_BIT_U_INT(dns_over_tcp_ptr) +#define DNSGetTCPLength(dns_over_tcp_ptr) GET_16_BIT_U_INT(dns_over_tcp_ptr) -#define DNSGetQueryIdentifier(dns_body) GET_16_BIT_U_INT((char *)(dns_body)) +#define DNSGetQueryIdentifier(dns_body) GET_16_BIT_U_INT((char *)(dns_body)) -#define DNSGetFlags(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 2) +#define DNSGetFlags(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 2) -#define DNSGetQuestionCount(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 4) +#define DNSGetQuestionCount(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 4) -#define DNSGetAnswerCount(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 6) +#define DNSGetAnswerCount(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 6) -#define DNSGetNameServerCount(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 8) +#define DNSGetNameServerCount(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 8) -#define DNSGetAdditionalCount(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 10) +#define DNSGetAdditionalCount(dns_body) GET_16_BIT_U_INT((char *)(dns_body) + 10) -#define DNSJumpHeader(dns_body) ((char *)(dns_body) + DNS_HEADER_LENGTH) +#define DNSJumpHeader(dns_body) ((char *)(dns_body) + DNS_HEADER_LENGTH) -#define DNSGetTTL(ans_start_ptr) GET_32_BIT_U_INT(DNSJumpOverName(ans_start_ptr) + 4) +#define DNSGetTTL(ans_start_ptr) GET_32_BIT_U_INT(DNSJumpOverName(ans_start_ptr) + 4) -#define DNSGetResourceDataLength(ans_start_ptr) GET_16_BIT_U_INT(DNSJumpOverName(ans_start_ptr) + 8) +#define DNSGetResourceDataLength(ans_start_ptr) GET_16_BIT_U_INT(DNSJumpOverName(ans_start_ptr) + 8) -#define DNSGetResourceDataPos(ans_start_ptr) (DNSJumpOverName((char *)(ans_start_ptr)) + 10) +#define DNSGetResourceDataPos(ans_start_ptr) (DNSJumpOverName((char *)(ans_start_ptr)) + 10) /* Common */ char *DNSJumpOverName(char *NameStart); @@ -41,102 +41,102 @@ int DNSGetHostName(const char *DNSBody, int DNSBodyLength, const char *NameStart int DNSGetHostNameLength(const char *DNSBody, int DNSBodyLength, const char *NameStart); -#define DNSGetRecordType(rec_start_ptr) ((rec_start_ptr) == NULL ? DNS_TYPE_UNKNOWN : GET_16_BIT_U_INT(DNSJumpOverName(rec_start_ptr))) +#define DNSGetRecordType(rec_start_ptr) ((rec_start_ptr) == NULL ? DNS_TYPE_UNKNOWN : GET_16_BIT_U_INT(DNSJumpOverName(rec_start_ptr))) -#define DNSIsLabelPointerStart(num) (((num) & 0xC0) == 0xC0) +#define DNSIsLabelPointerStart(num) (((num) & 0xC0) == 0xC0) -#define DNSLabelGetPointer(rec_start_ptr) ((rec_start_ptr) == NULL ? 0 : (int)((unsigned char *)(rec_start_ptr))[1] + (int)(((unsigned char *)(rec_start_ptr))[0] - 192) * 256) +#define DNSLabelGetPointer(rec_start_ptr) ((rec_start_ptr) == NULL ? 0 : (int)((unsigned char *)(rec_start_ptr))[1] + (int)(((unsigned char *)(rec_start_ptr))[0] - 192) * 256) -#define DNSGetRecordClass(rec_start_ptr) ((rec_start_ptr) == NULL ? DNS_CLASS_UNKNOWN : GET_16_BIT_U_INT(DNSJumpOverName(rec_start_ptr) + 2)) +#define DNSGetRecordClass(rec_start_ptr) ((rec_start_ptr) == NULL ? DNS_CLASS_UNKNOWN : GET_16_BIT_U_INT(DNSJumpOverName(rec_start_ptr) + 2)) #ifdef HOST_BIG_ENDIAN /* DNSMessageFlags, at 2-byte offset of a DNS header, is 2 bytes length. * https://tools.ietf.org/html/rfc6895 */ typedef struct _DNSMessageProperties{ - uint16_t Direction : 1; /* query (0), or response (1) */ + uint16_t Direction : 1; /* query (0), or response (1) */ - /* Type: - * 0 a standard query (QUERY). - * 1 an inverse query (IQUERY). - * 2 a server status request (STATUS). - * 3-15 reserved for future use */ - uint16_t Type : 4; + /* Type: + * 0 a standard query (QUERY). + * 1 an inverse query (IQUERY). + * 2 a server status request (STATUS). + * 3-15 reserved for future use */ + uint16_t Type : 4; - uint16_t AuthoritativeAnswer:1; + uint16_t AuthoritativeAnswer:1; - uint16_t TrunCation : 1; + uint16_t TrunCation : 1; - uint16_t RecursionDesired: 1; /* 0 no, 1 yes */ + uint16_t RecursionDesired: 1; /* 0 no, 1 yes */ - uint16_t RecursionAvailable: 1; /* 0 no, 1 yes */ + uint16_t RecursionAvailable: 1; /* 0 no, 1 yes */ - uint16_t Unused : 1; + uint16_t Unused : 1; - uint16_t AuthenticData : 1; + uint16_t AuthenticData : 1; - uint16_t CheckingDisabled: 1; + uint16_t CheckingDisabled: 1; - /* ResponseCode: - * 0 No error condition. - * 1 Format error - The name server was unable to interpret the query. - * 2 Server failure - The name server was unable to process this query due to a problem with the name server. - * 3 Name Error - Meaningful only for responses from an authoritative name server, this code signifies that the domain name referenced in the query does not exist. - * 4 Not Implemented - The name server does not support the requested kind of query. - * 5 Refused - The name server refuses to perform the specified operation for policy reasons. For example, a name server may not wish to provide the information to the particular requester, or a name server may not wish to perform a particular operation (e.g., zone transfer) for particular data. - * 6-15 Reserved for future use. */ - uint16_t ResponseCode : 4; + /* ResponseCode: + * 0 No error condition. + * 1 Format error - The name server was unable to interpret the query. + * 2 Server failure - The name server was unable to process this query due to a problem with the name server. + * 3 Name Error - Meaningful only for responses from an authoritative name server, this code signifies that the domain name referenced in the query does not exist. + * 4 Not Implemented - The name server does not support the requested kind of query. + * 5 Refused - The name server refuses to perform the specified operation for policy reasons. For example, a name server may not wish to provide the information to the particular requester, or a name server may not wish to perform a particular operation (e.g., zone transfer) for particular data. + * 6-15 Reserved for future use. */ + uint16_t ResponseCode : 4; }DNSFlags; #else typedef struct _DNSMessageProperties{ - uint16_t RecursionDesired: 1; /* 0 no, 1 yes */ + uint16_t RecursionDesired: 1; /* 0 no, 1 yes */ - uint16_t TrunCation : 1; + uint16_t TrunCation : 1; - uint16_t AuthoritativeAnswer:1; + uint16_t AuthoritativeAnswer:1; - /* Type: - * 0 a standard query (QUERY). - * 1 an inverse query (IQUERY). - * 2 a server status request (STATUS). - * 3-15 reserved for future use */ - uint16_t Type : 4; + /* Type: + * 0 a standard query (QUERY). + * 1 an inverse query (IQUERY). + * 2 a server status request (STATUS). + * 3-15 reserved for future use */ + uint16_t Type : 4; - uint16_t Direction : 1; /* query (0), or response (1) */ + uint16_t Direction : 1; /* query (0), or response (1) */ - /* ResponseCode: - * 0 No error condition. - * 1 Format error - The name server was unable to interpret the query. - * 2 Server failure - The name server was unable to process this query due to a problem with the name server. - * 3 Name Error - Meaningful only for responses from an authoritative name server, this code signifies that the domain name referenced in the query does not exist. - * 4 Not Implemented - The name server does not support the requested kind of query. - * 5 Refused - The name server refuses to perform the specified operation for policy reasons. For example, a name server may not wish to provide the information to the particular requester, or a name server may not wish to perform a particular operation (e.g., zone transfer) for particular data. - * 6-15 Reserved for future use. */ - uint16_t ResponseCode : 4; + /* ResponseCode: + * 0 No error condition. + * 1 Format error - The name server was unable to interpret the query. + * 2 Server failure - The name server was unable to process this query due to a problem with the name server. + * 3 Name Error - Meaningful only for responses from an authoritative name server, this code signifies that the domain name referenced in the query does not exist. + * 4 Not Implemented - The name server does not support the requested kind of query. + * 5 Refused - The name server refuses to perform the specified operation for policy reasons. For example, a name server may not wish to provide the information to the particular requester, or a name server may not wish to perform a particular operation (e.g., zone transfer) for particular data. + * 6-15 Reserved for future use. */ + uint16_t ResponseCode : 4; - uint16_t CheckingDisabled: 1; + uint16_t CheckingDisabled: 1; - uint16_t AuthenticData : 1; + uint16_t AuthenticData : 1; - uint16_t Unused : 1; + uint16_t Unused : 1; - uint16_t RecursionAvailable: 1; /* 0 no, 1 yes */ + uint16_t RecursionAvailable: 1; /* 0 no, 1 yes */ }DNSFlags; #endif typedef struct _DNSHeader{ - uint16_t Identifier; - DNSFlags Flags; - uint16_t QuestionCount; - uint16_t AnswerCount; - uint16_t NameServerCount; - uint16_t AdditionalCount; + uint16_t Identifier; + DNSFlags Flags; + uint16_t QuestionCount; + uint16_t AnswerCount; + uint16_t NameServerCount; + uint16_t AdditionalCount; }DNSHeader; -#define DNSGetHeader(dns_body_ptr) ((DNSHeader *)(dns_body_ptr)) +#define DNSGetHeader(dns_body_ptr) ((DNSHeader *)(dns_body_ptr)) /* Convert a DNS message to text */ char *GetAllAnswers(char *DNSBody, int DNSBodyLength, char *Buffer, int BufferLength); diff --git a/dnsrelated.c b/dnsrelated.c index 25701c5a..456e3abf 100755 --- a/dnsrelated.c +++ b/dnsrelated.c @@ -3,106 +3,106 @@ /* http://en.wikipedia.org/wiki/List_of_DNS_record_types */ const DNSTypeAndName DNSTypeList[] = { - {0, NULL}, - {1, "IPv4 Address"}, - {2, "Name Server"}, - {5, "Canonical Name"}, - {6, "start of authority"}, - {12, "Domain pointer"}, - {13, "Host Information"}, - {15, "MX"}, - {16, "TXT"}, - {17, "RP"}, - {18, "AFSDB"}, - {24, "SIG"}, - {25, "KEY"}, - {28, "IPv6 Address"}, - {29, "LOC"}, - {33, "SRV"}, - {35, "NAPTR"}, - {36, "KX"}, - {37, "CERT"}, - {39, "DNAME"}, - {41, "OPT"}, - {42, "APL"}, - {43, "DS"}, - {44, "SSHFP"}, - {45, "IPSECKEY"}, - {46, "RRSIG"}, - {47, "NSEC"}, - {48, "DNSKEY"}, - {49, "DHCID"}, - {50, "NSEC3"}, - {51, "NSEC3PARAM"}, - {55, "HIP"}, - {64, "SVCB"}, - {65, "HTTPS"}, - {99, "SPF"}, - {249, "TKEY"}, - {250, "TSIG"}, - {251, "IXFR"}, - {252, "AXFR"}, - {255, "*"}, - {32768, "TA"}, - {32769, "DLV"} + {0, NULL}, + {1, "IPv4 Address"}, + {2, "Name Server"}, + {5, "Canonical Name"}, + {6, "start of authority"}, + {12, "Domain pointer"}, + {13, "Host Information"}, + {15, "MX"}, + {16, "TXT"}, + {17, "RP"}, + {18, "AFSDB"}, + {24, "SIG"}, + {25, "KEY"}, + {28, "IPv6 Address"}, + {29, "LOC"}, + {33, "SRV"}, + {35, "NAPTR"}, + {36, "KX"}, + {37, "CERT"}, + {39, "DNAME"}, + {41, "OPT"}, + {42, "APL"}, + {43, "DS"}, + {44, "SSHFP"}, + {45, "IPSECKEY"}, + {46, "RRSIG"}, + {47, "NSEC"}, + {48, "DNSKEY"}, + {49, "DHCID"}, + {50, "NSEC3"}, + {51, "NSEC3PARAM"}, + {55, "HIP"}, + {64, "SVCB"}, + {65, "HTTPS"}, + {99, "SPF"}, + {249, "TKEY"}, + {250, "TSIG"}, + {251, "IXFR"}, + {252, "AXFR"}, + {255, "*"}, + {32768, "TA"}, + {32769, "DLV"} }; /* http://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml */ const DNSSECAlgorithm DNSSECAlgorithmList[] = { - {0, "(reserved)"}, - {1, "RSA/MD5"}, - {2, "Diffie-Hellman"}, - {3, "DSA/SHA-1"}, - {4, "Elliptic Curve"}, - {5, "RSA/SHA-1"}, - {6, "DSA-NSEC3-SHA1"}, - {7, "RSASHA1-NSEC3-SHA1"}, - {8, "RSA/SHA-256"}, - {9, "(reserved)"}, - {10, "RSA/SHA-512"}, - {11, "(reserved)"}, - {12, "GOST R 34.10-2001"}, - {13, "ECDSA Curve P-256 with SHA-256"}, - {14, "ECDSA Curve P-384 with SHA-384"}, + {0, "(reserved)"}, + {1, "RSA/MD5"}, + {2, "Diffie-Hellman"}, + {3, "DSA/SHA-1"}, + {4, "Elliptic Curve"}, + {5, "RSA/SHA-1"}, + {6, "DSA-NSEC3-SHA1"}, + {7, "RSASHA1-NSEC3-SHA1"}, + {8, "RSA/SHA-256"}, + {9, "(reserved)"}, + {10, "RSA/SHA-512"}, + {11, "(reserved)"}, + {12, "GOST R 34.10-2001"}, + {13, "ECDSA Curve P-256 with SHA-256"}, + {14, "ECDSA Curve P-384 with SHA-384"}, - {252, "Indirect"}, - {253, "Private"}, - {254, "Private"}, - {255, "(reserved)"} + {252, "Indirect"}, + {253, "Private"}, + {254, "Private"}, + {255, "(reserved)"} }; const char *DNSGetTypeName(uint16_t Num) { - int loop; + int loop; - for(loop = 0; loop < sizeof(DNSTypeList) / sizeof(DNSTypeAndName); ++loop) - { - if( DNSTypeList[loop].Num == Num ) - { - return DNSTypeList[loop].Name; - } - } + for(loop = 0; loop < sizeof(DNSTypeList) / sizeof(DNSTypeAndName); ++loop) + { + if( DNSTypeList[loop].Num == Num ) + { + return DNSTypeList[loop].Name; + } + } - return "UNKNOWN"; + return "UNKNOWN"; } static int DNSSECAlgorithm_Compare(DNSSECAlgorithm *Key, DNSSECAlgorithm *Element) { - return Key->Num - Element->Num; + return Key->Num - Element->Num; } const char *DNSSECGetAlgorithmName(int Num) { - DNSSECAlgorithm Key = {Num, NULL}; + DNSSECAlgorithm Key = {Num, NULL}; - DNSSECAlgorithm *Result = NULL; + DNSSECAlgorithm *Result = NULL; - Result = bsearch(&Key, DNSSECAlgorithmList, sizeof(DNSSECAlgorithmList) / sizeof(DNSSECAlgorithm), sizeof(DNSSECAlgorithm), (int (*)(const void *, const void *))DNSSECAlgorithm_Compare); + Result = bsearch(&Key, DNSSECAlgorithmList, sizeof(DNSSECAlgorithmList) / sizeof(DNSSECAlgorithm), sizeof(DNSSECAlgorithm), (int (*)(const void *, const void *))DNSSECAlgorithm_Compare); - if( Result == NULL ) - { - return "UNKNOWN"; - } else { - return Result->Name; - } + if( Result == NULL ) + { + return "UNKNOWN"; + } else { + return Result->Name; + } } diff --git a/dnsrelated.h b/dnsrelated.h index b4266707..dfeba4df 100755 --- a/dnsrelated.h +++ b/dnsrelated.h @@ -4,65 +4,65 @@ #include "common.h" typedef enum _DNSRecordType{ - DNS_TYPE_UNKNOWN = 0, - DNS_TYPE_A = 1, - DNS_TYPE_NS = 2, - DNS_TYPE_CNAME = 5, - DNS_TYPE_SOA = 6, - DNS_TYPE_PTR = 12, - DNS_TYPE_HINFO = 13, - DNS_TYPE_MX = 15, - DNS_TYPE_TXT = 16, - DNS_TYPE_RP = 17, - DNS_TYPE_AFSDB = 18, - DNS_TYPE_SIG = 24, - DNS_TYPE_KEY = 25, - DNS_TYPE_AAAA = 28, - DNS_TYPE_LOC = 29, - DNS_TYPE_SRV = 33, - DNS_TYPE_NAPTR = 35, - DNS_TYPE_KX = 36, - DNS_TYPE_CERT = 37, - DNS_TYPE_DNAME = 39, - DNS_TYPE_OPT = 41, - DNS_TYPE_APL = 42, - DNS_TYPE_DS = 43, - DNS_TYPE_SSHFP = 44, - DNS_TYPE_IPSECKEY = 45, - DNS_TYPE_RRSIG = 46, - DNS_TYPE_NSEC = 47, - DNS_TYPE_DNSKEY = 48, - DNS_TYPE_DHCID = 49, - DNS_TYPE_NSEC3 = 50, - DNS_TYPE_NSEC3PARAM = 51, - DNS_TYPE_HIP = 55, - DNS_TYPE_SVCB = 64, - DNS_TYPE_HTTPS = 65, - DNS_TYPE_SPF = 99, - DNS_TYPE_TKEY = 249, - DNS_TYPE_TSIG = 250, - DNS_TYPE_IXFR = 251, - DNS_TYPE_AXFR = 252, - DNS_TYPE_ANY = 255, - DNS_TYPE_TA = 32768, - DNS_TYPE_DLV = 32769, + DNS_TYPE_UNKNOWN = 0, + DNS_TYPE_A = 1, + DNS_TYPE_NS = 2, + DNS_TYPE_CNAME = 5, + DNS_TYPE_SOA = 6, + DNS_TYPE_PTR = 12, + DNS_TYPE_HINFO = 13, + DNS_TYPE_MX = 15, + DNS_TYPE_TXT = 16, + DNS_TYPE_RP = 17, + DNS_TYPE_AFSDB = 18, + DNS_TYPE_SIG = 24, + DNS_TYPE_KEY = 25, + DNS_TYPE_AAAA = 28, + DNS_TYPE_LOC = 29, + DNS_TYPE_SRV = 33, + DNS_TYPE_NAPTR = 35, + DNS_TYPE_KX = 36, + DNS_TYPE_CERT = 37, + DNS_TYPE_DNAME = 39, + DNS_TYPE_OPT = 41, + DNS_TYPE_APL = 42, + DNS_TYPE_DS = 43, + DNS_TYPE_SSHFP = 44, + DNS_TYPE_IPSECKEY = 45, + DNS_TYPE_RRSIG = 46, + DNS_TYPE_NSEC = 47, + DNS_TYPE_DNSKEY = 48, + DNS_TYPE_DHCID = 49, + DNS_TYPE_NSEC3 = 50, + DNS_TYPE_NSEC3PARAM = 51, + DNS_TYPE_HIP = 55, + DNS_TYPE_SVCB = 64, + DNS_TYPE_HTTPS = 65, + DNS_TYPE_SPF = 99, + DNS_TYPE_TKEY = 249, + DNS_TYPE_TSIG = 250, + DNS_TYPE_IXFR = 251, + DNS_TYPE_AXFR = 252, + DNS_TYPE_ANY = 255, + DNS_TYPE_TA = 32768, + DNS_TYPE_DLV = 32769, }DNSRecordType; typedef enum _DNSRecordClass{ - DNS_CLASS_UNKNOWN = 0, - DNS_CLASS_IN = 1, - DNS_CLASS_CH = 3, - DNS_CLASS_ANY = 255, + DNS_CLASS_UNKNOWN = 0, + DNS_CLASS_IN = 1, + DNS_CLASS_CH = 3, + DNS_CLASS_ANY = 255, }DNSRecordClass; typedef struct _DNSTypeName{ - DNSRecordType Num; - const char *Name; + DNSRecordType Num; + const char *Name; }DNSTypeAndName; typedef struct _DNSSECAlgorithm { - int Num; - const char *Name; + int Num; + const char *Name; } DNSSECAlgorithm; extern const DNSTypeAndName DNSTypeList[]; diff --git a/domainstatistic.c b/domainstatistic.c index c829f3f0..3776f1b1 100755 --- a/domainstatistic.c +++ b/domainstatistic.c @@ -8,93 +8,93 @@ #include "logs.h" typedef struct _DomainInfo{ - int Count; - int Refused; - int Hosts; - int Cache; - int Udp; - int Tcp; - int BlockedMsg; + int Count; + int Refused; + int Hosts; + int Cache; + int Udp; + int Tcp; + int BlockedMsg; } DomainInfo; typedef struct _RankList{ - const char *Domain; - DomainInfo *Info; + const char *Domain; + DomainInfo *Info; } RankList; -static EFFECTIVE_LOCK StatisticLock; +static EFFECTIVE_LOCK StatisticLock; -static StringChunk MainChunk; +static StringChunk MainChunk; -static FILE *MainFile = NULL; +static FILE *MainFile = NULL; -static unsigned long int InitTime_Num; +static unsigned long int InitTime_Num; -static const char *PreOutput = NULL; /* malloced */ -static const char *PostOutput = NULL; +static const char *PreOutput = NULL; /* malloced */ +static const char *PostOutput = NULL; -volatile static BOOL SkipStatistic = FALSE; +volatile static BOOL SkipStatistic = FALSE; static int GetPreAndPost(ConfigFileInfo *ConfigInfo) { - const char *TemplateFile = ConfigGetRawString(ConfigInfo, "DomainStatisticTempletFile"); - const char *InsertionPosString = ConfigGetRawString(ConfigInfo, "StatisticInsertionPosition"); - char *ip = NULL; - int FileSize; - char *FileContent = NULL; - if( TemplateFile == NULL ) - { - return -1; - } - - FileSize = GetFileSizePortable(TemplateFile); - if( FileSize <= 0 ) - { - return -1; - } - - FileContent = SafeMalloc(FileSize + 1); - if( FileContent == NULL ) - { - return -1; - } - - memset(FileContent, 0, FileSize + 1); - - if( GetTextFileContent(TemplateFile, FileContent) != 0 ) - { - SafeFree(FileContent); - return -1; - } - - ip = strstr(FileContent, InsertionPosString); - if( ip == NULL ) - { - SafeFree(FileContent); - return -1; - } - - PreOutput = FileContent; - PostOutput = ip + strlen(InsertionPosString); - *ip = '\0'; - - return 0; + const char *TemplateFile = ConfigGetRawString(ConfigInfo, "DomainStatisticTempletFile"); + const char *InsertionPosString = ConfigGetRawString(ConfigInfo, "StatisticInsertionPosition"); + char *ip = NULL; + int FileSize; + char *FileContent = NULL; + if( TemplateFile == NULL ) + { + return -1; + } + + FileSize = GetFileSizePortable(TemplateFile); + if( FileSize <= 0 ) + { + return -1; + } + + FileContent = SafeMalloc(FileSize + 1); + if( FileContent == NULL ) + { + return -1; + } + + memset(FileContent, 0, FileSize + 1); + + if( GetTextFileContent(TemplateFile, FileContent) != 0 ) + { + SafeFree(FileContent); + return -1; + } + + ip = strstr(FileContent, InsertionPosString); + if( ip == NULL ) + { + SafeFree(FileContent); + return -1; + } + + PreOutput = FileContent; + PostOutput = ip + strlen(InsertionPosString); + *ip = '\0'; + + return 0; } static int DomainStatistic_Works(void *Unused, void *Unused2) { - const char *Str; - int32_t Enum_Start; + const char *Str; + int32_t Enum_Start; - DomainInfo *Info; - DomainInfo Sum; + DomainInfo *Info; + DomainInfo Sum; - unsigned long int GenerateTime_Num; + unsigned long int GenerateTime_Num; - if( MainFile == NULL ) - { - return 0; - } + if( MainFile == NULL ) + { + return 0; + } rewind(MainFile); @@ -105,9 +105,9 @@ static int DomainStatistic_Works(void *Unused, void *Unused2) fprintf(MainFile, "%s", PreOutput); fprintf(MainFile, "", Sum.Count, @@ -191,47 +191,47 @@ static int DomainStatistic_Works(void *Unused, void *Unused2) int DomainStatistic_Init(ConfigFileInfo *ConfigInfo) { BOOL DomainStatistic = ConfigGetBoolean(ConfigInfo, "DomainStatistic"); - int OutputInterval; - char FilePath[1024]; + int OutputInterval; + char FilePath[1024]; - if( !DomainStatistic ) + if( !DomainStatistic ) { return 0; } OutputInterval = ConfigGetInt32(ConfigInfo, "StatisticUpdateInterval"); - if( OutputInterval < 1 ) - { + if( OutputInterval < 1 ) + { ERRORMSG("`StatisticUpdateInterval' should be positive.\n"); - return 1; - } + return 1; + } - if( GetPreAndPost(ConfigInfo) != 0 ) - { - WARNING("Domain statistic init failed, it may due to lack of memory or templet file.\n"); - return 0; - } + if( GetPreAndPost(ConfigInfo) != 0 ) + { + WARNING("Domain statistic init failed, it may due to lack of memory or templet file.\n"); + return 0; + } - GetFileDirectory(FilePath); - strcat(FilePath, PATH_SLASH_STR); - strcat(FilePath, "statistic.html"); + GetFileDirectory(FilePath); + strcat(FilePath, PATH_SLASH_STR); + strcat(FilePath, "statistic.html"); - MainFile = fopen(FilePath, "w"); + MainFile = fopen(FilePath, "w"); - if( MainFile == NULL ) - { - ERRORMSG("Writing %s failed.\n", FilePath); - return 3; - } + if( MainFile == NULL ) + { + ERRORMSG("Writing %s failed.\n", FilePath); + return 3; + } - EFFECTIVE_LOCK_INIT(StatisticLock); - StringChunk_Init(&MainChunk, NULL); + EFFECTIVE_LOCK_INIT(StatisticLock); + StringChunk_Init(&MainChunk, NULL); - InitTime_Num = time(NULL); - SkipStatistic = FALSE; + InitTime_Num = time(NULL); + SkipStatistic = FALSE; - TimedTask_Add(TRUE, + TimedTask_Add(TRUE, FALSE, OutputInterval * 1000, DomainStatistic_Works, @@ -240,109 +240,109 @@ int DomainStatistic_Init(ConfigFileInfo *ConfigInfo) FALSE ); - return 0; + return 0; } int DomainStatistic_Add(IHeader *h, StatisticType Type) { - DomainInfo *ExistInfo; + DomainInfo *ExistInfo; - if( MainFile == NULL || h == NULL ) - { - return 0; - } + if( MainFile == NULL || h == NULL ) + { + return 0; + } - EFFECTIVE_LOCK_GET(StatisticLock); + EFFECTIVE_LOCK_GET(StatisticLock); - if( SkipStatistic == FALSE ) - { + if( SkipStatistic == FALSE ) + { - if( StringChunk_Match(&MainChunk, + if( StringChunk_Match(&MainChunk, h->Domain, &(h->HashValue), (void **)&ExistInfo ) == FALSE ) - { - DomainInfo NewInfo; - - memset(&NewInfo, 0, sizeof(DomainInfo)); - - switch( Type ) - { - case STATISTIC_TYPE_REFUSED: - NewInfo.Count = 1; - NewInfo.Refused = 1; - break; - - case STATISTIC_TYPE_HOSTS: - NewInfo.Count = 1; - NewInfo.Hosts = 1; - break; - - case STATISTIC_TYPE_CACHE: - NewInfo.Count = 1; - NewInfo.Cache = 1; - break; - - case STATISTIC_TYPE_UDP: - NewInfo.Count = 1; - NewInfo.Udp = 1; - break; - - case STATISTIC_TYPE_TCP: - NewInfo.Count = 1; - NewInfo.Tcp = 1; - break; - - case STATISTIC_TYPE_BLOCKEDMSG: - NewInfo.Count = 0; - NewInfo.BlockedMsg = 1; - break; - - } - - StringChunk_Add(&MainChunk, h->Domain, (const char *)&NewInfo, sizeof(DomainInfo)); - } else { - if( ExistInfo != NULL ) - { - switch( Type ) - { - case STATISTIC_TYPE_REFUSED: - ++(ExistInfo->Count); - ++(ExistInfo->Refused); - break; - - case STATISTIC_TYPE_HOSTS: - ++(ExistInfo->Count); - ++(ExistInfo->Hosts); - break; - - case STATISTIC_TYPE_CACHE: - ++(ExistInfo->Count); - ++(ExistInfo->Cache); - break; - - case STATISTIC_TYPE_UDP: - ++(ExistInfo->Count); - ++(ExistInfo->Udp); - break; - - case STATISTIC_TYPE_TCP: - ++(ExistInfo->Count); - ++(ExistInfo->Tcp); - break; - - case STATISTIC_TYPE_BLOCKEDMSG: - ++(ExistInfo->BlockedMsg); - break; - } - } - } - - } - - EFFECTIVE_LOCK_RELEASE(StatisticLock); - - return 0; + { + DomainInfo NewInfo; + + memset(&NewInfo, 0, sizeof(DomainInfo)); + + switch( Type ) + { + case STATISTIC_TYPE_REFUSED: + NewInfo.Count = 1; + NewInfo.Refused = 1; + break; + + case STATISTIC_TYPE_HOSTS: + NewInfo.Count = 1; + NewInfo.Hosts = 1; + break; + + case STATISTIC_TYPE_CACHE: + NewInfo.Count = 1; + NewInfo.Cache = 1; + break; + + case STATISTIC_TYPE_UDP: + NewInfo.Count = 1; + NewInfo.Udp = 1; + break; + + case STATISTIC_TYPE_TCP: + NewInfo.Count = 1; + NewInfo.Tcp = 1; + break; + + case STATISTIC_TYPE_BLOCKEDMSG: + NewInfo.Count = 0; + NewInfo.BlockedMsg = 1; + break; + + } + + StringChunk_Add(&MainChunk, h->Domain, (const char *)&NewInfo, sizeof(DomainInfo)); + } else { + if( ExistInfo != NULL ) + { + switch( Type ) + { + case STATISTIC_TYPE_REFUSED: + ++(ExistInfo->Count); + ++(ExistInfo->Refused); + break; + + case STATISTIC_TYPE_HOSTS: + ++(ExistInfo->Count); + ++(ExistInfo->Hosts); + break; + + case STATISTIC_TYPE_CACHE: + ++(ExistInfo->Count); + ++(ExistInfo->Cache); + break; + + case STATISTIC_TYPE_UDP: + ++(ExistInfo->Count); + ++(ExistInfo->Udp); + break; + + case STATISTIC_TYPE_TCP: + ++(ExistInfo->Count); + ++(ExistInfo->Tcp); + break; + + case STATISTIC_TYPE_BLOCKEDMSG: + ++(ExistInfo->BlockedMsg); + break; + } + } + } + + } + + EFFECTIVE_LOCK_RELEASE(StatisticLock); + + return 0; } diff --git a/domainstatistic.h b/domainstatistic.h index 38d69369..01ac599b 100755 --- a/domainstatistic.h +++ b/domainstatistic.h @@ -5,13 +5,13 @@ #include "iheader.h" typedef enum _StatisticType{ - STATISTIC_TYPE_REFUSED = 0, - STATISTIC_TYPE_HOSTS, - STATISTIC_TYPE_CACHE, - STATISTIC_TYPE_UDP, - STATISTIC_TYPE_TCP, + STATISTIC_TYPE_REFUSED = 0, + STATISTIC_TYPE_HOSTS, + STATISTIC_TYPE_CACHE, + STATISTIC_TYPE_UDP, + STATISTIC_TYPE_TCP, - STATISTIC_TYPE_BLOCKEDMSG + STATISTIC_TYPE_BLOCKEDMSG } StatisticType; int DomainStatistic_Init(ConfigFileInfo *ConfigInfo); diff --git a/downloader.c b/downloader.c index 3cafc0b6..8dbbbde4 100755 --- a/downloader.c +++ b/downloader.c @@ -1,4 +1,4 @@ -#ifndef WIN32 +#ifndef WIN32 #ifndef DOWNLOAD_LIBCURL #ifndef DOWNLOAD_WGET #ifndef NODOWNLOAD @@ -28,158 +28,158 @@ #include "downloader.h" #include "logs.h" -int GetFromInternet_MultiFiles(const char **URLs, - const char *File, - int RetryInterval, - int RetryTimes, - void (*ErrorCallBack)(int ErrorCode, const char *URL, const char *File), - void (*SuccessCallBack)(const char *URL, const char *File) - ) +int GetFromInternet_MultiFiles(const char **URLs, + const char *File, + int RetryInterval, + int RetryTimes, + void (*ErrorCallBack)(int ErrorCode, const char *URL, const char *File), + void (*SuccessCallBack)(const char *URL, const char *File) + ) { - int State = FALSE; - FILE *fp; - char *TempFile; - - TempFile = SafeMalloc(strlen(File) + sizeof(".tmp") + 1); - if( TempFile == NULL ) - { - ERRORMSG("Cannot create temp file %s\n", TempFile); - return -1; - } - - strcpy(TempFile, File); - strcat(TempFile, ".tmp"); - - fp = fopen(TempFile, "w"); - if( fp != NULL ) - { - fclose(fp); - } else { - ERRORMSG("Cannot create temp file %s\n", TempFile); - SafeFree(TempFile); - return -2; - } - - while( *URLs != NULL ) - { - State |= !GetFromInternet_SingleFile(*URLs, TempFile, TRUE, RetryInterval, RetryTimes, ErrorCallBack, SuccessCallBack); - - fp = fopen(TempFile, "a+"); - if( fp != NULL ) - { - fputc('\n', fp); - fclose(fp); - } else { - break; - } - - ++URLs; - } - - if( State && TRUE ) - { - remove(File); - rename(TempFile, File); - } - - SafeFree(TempFile); - return !State; + int State = FALSE; + FILE *fp; + char *TempFile; + + TempFile = SafeMalloc(strlen(File) + sizeof(".tmp") + 1); + if( TempFile == NULL ) + { + ERRORMSG("Cannot create temp file %s\n", TempFile); + return -1; + } + + strcpy(TempFile, File); + strcat(TempFile, ".tmp"); + + fp = fopen(TempFile, "w"); + if( fp != NULL ) + { + fclose(fp); + } else { + ERRORMSG("Cannot create temp file %s\n", TempFile); + SafeFree(TempFile); + return -2; + } + + while( *URLs != NULL ) + { + State |= !GetFromInternet_SingleFile(*URLs, TempFile, TRUE, RetryInterval, RetryTimes, ErrorCallBack, SuccessCallBack); + + fp = fopen(TempFile, "a+"); + if( fp != NULL ) + { + fputc('\n', fp); + fclose(fp); + } else { + break; + } + + ++URLs; + } + + if( State && TRUE ) + { + remove(File); + rename(TempFile, File); + } + + SafeFree(TempFile); + return !State; } -int GetFromInternet_SingleFile(const char *URL, - const char *File, - BOOL Append, - int RetryInterval, - int RetryTimes, - void (*ErrorCallBack)(int ErrorCode, const char *URL, const char *File), - void (*SuccessCallBack)(const char *URL, const char *File) - ) +int GetFromInternet_SingleFile(const char *URL, + const char *File, + BOOL Append, + int RetryInterval, + int RetryTimes, + void (*ErrorCallBack)(int ErrorCode, const char *URL, const char *File), + void (*SuccessCallBack)(const char *URL, const char *File) + ) { - int DownloadState = 0; - - if( strncmp(URL, "file", 4) == 0 ) - { - char LocalPath[384]; - - if( GetLocalPathFromURL(URL, LocalPath, sizeof(LocalPath)) == NULL ) - { - if( ErrorCallBack != NULL ) - { - ErrorCallBack(0, URL, File); - } - - return -1; - } - - if( CopyAFile(LocalPath, File, Append) != 0 ) - { - if( ErrorCallBack != NULL ) - { - ErrorCallBack(0, URL, File); - } - - return -1; - } - - if( SuccessCallBack != NULL ) - { - SuccessCallBack(URL, File); - } - - return 0; - } else { - int Ret = -1; - char *TempFile; - TempFile = SafeMalloc(strlen(File) + sizeof(".tmp") + 1); - if( TempFile == NULL ) - { - return -1; - } - strcpy(TempFile, File); - strcat(TempFile, ".tmp"); - - while( RetryTimes != 0 ) - { - DownloadState = GetFromInternet_Base(URL, TempFile); - if( DownloadState == 0 ) - { - if( SuccessCallBack != NULL ) - { - SuccessCallBack(URL, File); - } - - if( CopyAFile(TempFile, File, Append) != 0 ) - { - if( ErrorCallBack != NULL ) - { - ErrorCallBack(0, URL, File); - } - - Ret = -1; - break; - } else { - Ret = 0; - break; - } - } else { - if( RetryTimes > 0 ) - { - --RetryTimes; - } - - if( ErrorCallBack != NULL ) - { - ErrorCallBack((-1) * DownloadState, URL, File); - } - - SLEEP(RetryInterval * 1000); - } - } - - remove(TempFile); - SafeFree(TempFile); - return Ret; - } + int DownloadState = 0; + + if( strncmp(URL, "file", 4) == 0 ) + { + char LocalPath[384]; + + if( GetLocalPathFromURL(URL, LocalPath, sizeof(LocalPath)) == NULL ) + { + if( ErrorCallBack != NULL ) + { + ErrorCallBack(0, URL, File); + } + + return -1; + } + + if( CopyAFile(LocalPath, File, Append) != 0 ) + { + if( ErrorCallBack != NULL ) + { + ErrorCallBack(0, URL, File); + } + + return -1; + } + + if( SuccessCallBack != NULL ) + { + SuccessCallBack(URL, File); + } + + return 0; + } else { + int Ret = -1; + char *TempFile; + TempFile = SafeMalloc(strlen(File) + sizeof(".tmp") + 1); + if( TempFile == NULL ) + { + return -1; + } + strcpy(TempFile, File); + strcat(TempFile, ".tmp"); + + while( RetryTimes != 0 ) + { + DownloadState = GetFromInternet_Base(URL, TempFile); + if( DownloadState == 0 ) + { + if( SuccessCallBack != NULL ) + { + SuccessCallBack(URL, File); + } + + if( CopyAFile(TempFile, File, Append) != 0 ) + { + if( ErrorCallBack != NULL ) + { + ErrorCallBack(0, URL, File); + } + + Ret = -1; + break; + } else { + Ret = 0; + break; + } + } else { + if( RetryTimes > 0 ) + { + --RetryTimes; + } + + if( ErrorCallBack != NULL ) + { + ErrorCallBack((-1) * DownloadState, URL, File); + } + + SLEEP(RetryInterval * 1000); + } + } + + remove(TempFile); + SafeFree(TempFile); + return Ret; + } } #ifdef DOWNLOAD_LIBCURL @@ -189,129 +189,129 @@ static size_t WriteFileCallback(void *Contents, void *FileDes ) { - FILE *fp = (FILE *)FileDes; - fwrite(Contents, Size, nmemb, fp); - return Size * nmemb; + FILE *fp = (FILE *)FileDes; + fwrite(Contents, Size, nmemb, fp); + return Size * nmemb; } #endif /* DOWNLOAD_LIBCURL */ int GetFromInternet_Base(const char *URL, const char *File) { #ifndef NODOWNLOAD -# ifdef WIN32 - FILE *fp; - HINTERNET webopen = NULL, - webopenurl = NULL; - BOOL ReadFlag; - DWORD ReadedLength; - DWORD TotalLength = 0; - char Buffer[4096]; - int ret = -1; - int TimeOut = 30000; - - webopen = InternetOpen("dnsforwarder", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); - if( webopen == NULL ){ - ret = -1 * GetLastError(); - InternetCloseHandle(webopen); - return ret; - } - - webopenurl = InternetOpenUrl(webopen, URL, NULL, 0, INTERNET_FLAG_RELOAD, 0); - if( webopenurl == NULL ){ - ret = -1 * GetLastError(); - InternetCloseHandle(webopenurl); - InternetCloseHandle(webopen); - return ret; - } - - InternetSetOption(webopenurl, INTERNET_OPTION_CONNECT_TIMEOUT, &TimeOut, sizeof(TimeOut)); - - fp = fopen(File, "wb" ); - if( fp == NULL ) - { - ret = -1 * GetLastError(); - InternetCloseHandle(webopenurl); - InternetCloseHandle(webopen); - return ret; - } - - while(1) - { - ReadedLength = 0; - ReadFlag = InternetReadFile(webopenurl, Buffer, sizeof(Buffer), &ReadedLength); - - if( ReadFlag == FALSE ){ - ret = -1 * GetLastError(); - InternetCloseHandle(webopenurl); - InternetCloseHandle(webopen); - fclose(fp); - return ret; - } - - if( ReadedLength == 0 ) - break; - - fwrite(Buffer, 1, ReadedLength, fp); - - TotalLength += ReadedLength; - } - - InternetCloseHandle(webopenurl); - InternetCloseHandle(webopen); - fclose(fp); - - return 0; -# else /* WIN32 */ - -# ifdef DOWNLOAD_LIBCURL - CURL *curl; - CURLcode res; - - FILE *fp; - - fp = fopen(File, "w"); - if( fp == NULL ) - { - return -1; - } - - curl = curl_easy_init(); - if( curl == NULL ) - { - fclose(fp); - return -2; - } - - curl_easy_setopt(curl, CURLOPT_URL, URL); - curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1l); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteFileCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); - - curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); - curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); - - res = curl_easy_perform(curl); - if( res != CURLE_OK ) - { - curl_easy_cleanup(curl); - fclose(fp); - return -3; - } else { - curl_easy_cleanup(curl); - fclose(fp); - return 0; - } -# endif /* DOWNLOAD_LIBCURL */ -# ifdef DOWNLOAD_WGET - char Cmd[2048]; - - sprintf(Cmd, "wget -t 2 -T 60 -q --no-check-certificate %s -O %s ", URL, File); - - return Execute(Cmd); -# endif /* DOWNLOAD_WGET */ -# endif /* WIN32 */ +# ifdef WIN32 + FILE *fp; + HINTERNET webopen = NULL, + webopenurl = NULL; + BOOL ReadFlag; + DWORD ReadedLength; + DWORD TotalLength = 0; + char Buffer[4096]; + int ret = -1; + int TimeOut = 30000; + + webopen = InternetOpen("dnsforwarder", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); + if( webopen == NULL ){ + ret = -1 * GetLastError(); + InternetCloseHandle(webopen); + return ret; + } + + webopenurl = InternetOpenUrl(webopen, URL, NULL, 0, INTERNET_FLAG_RELOAD, 0); + if( webopenurl == NULL ){ + ret = -1 * GetLastError(); + InternetCloseHandle(webopenurl); + InternetCloseHandle(webopen); + return ret; + } + + InternetSetOption(webopenurl, INTERNET_OPTION_CONNECT_TIMEOUT, &TimeOut, sizeof(TimeOut)); + + fp = fopen(File, "wb" ); + if( fp == NULL ) + { + ret = -1 * GetLastError(); + InternetCloseHandle(webopenurl); + InternetCloseHandle(webopen); + return ret; + } + + while(1) + { + ReadedLength = 0; + ReadFlag = InternetReadFile(webopenurl, Buffer, sizeof(Buffer), &ReadedLength); + + if( ReadFlag == FALSE ){ + ret = -1 * GetLastError(); + InternetCloseHandle(webopenurl); + InternetCloseHandle(webopen); + fclose(fp); + return ret; + } + + if( ReadedLength == 0 ) + break; + + fwrite(Buffer, 1, ReadedLength, fp); + + TotalLength += ReadedLength; + } + + InternetCloseHandle(webopenurl); + InternetCloseHandle(webopen); + fclose(fp); + + return 0; +# else /* WIN32 */ + +# ifdef DOWNLOAD_LIBCURL + CURL *curl; + CURLcode res; + + FILE *fp; + + fp = fopen(File, "w"); + if( fp == NULL ) + { + return -1; + } + + curl = curl_easy_init(); + if( curl == NULL ) + { + fclose(fp); + return -2; + } + + curl_easy_setopt(curl, CURLOPT_URL, URL); + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1l); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteFileCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); + + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + + res = curl_easy_perform(curl); + if( res != CURLE_OK ) + { + curl_easy_cleanup(curl); + fclose(fp); + return -3; + } else { + curl_easy_cleanup(curl); + fclose(fp); + return 0; + } +# endif /* DOWNLOAD_LIBCURL */ +# ifdef DOWNLOAD_WGET + char Cmd[2048]; + + sprintf(Cmd, "wget -t 2 -T 60 -q --no-check-certificate %s -O %s ", URL, File); + + return Execute(Cmd); +# endif /* DOWNLOAD_WGET */ +# endif /* WIN32 */ #else /* NODOWNLOAD */ WARNING("No downloader implemented.\n"); - return -1; + return -1; #endif /* NODOWNLOAD */ } diff --git a/downloader.h b/downloader.h index d15a1899..6b28ba7e 100755 --- a/downloader.h +++ b/downloader.h @@ -3,22 +3,22 @@ #include "common.h" -int GetFromInternet_MultiFiles(const char **URLs, - const char *File, - int RetryInterval, - int RetryTimes, - void (*ErrorCallBack)(int ErrorCode, const char *URL, const char *File), - void (*SuccessCallBack)(const char *URL, const char *File) - ); +int GetFromInternet_MultiFiles(const char **URLs, + const char *File, + int RetryInterval, + int RetryTimes, + void (*ErrorCallBack)(int ErrorCode, const char *URL, const char *File), + void (*SuccessCallBack)(const char *URL, const char *File) + ); -int GetFromInternet_SingleFile(const char *URL, - const char *File, - BOOL Append, - int RetryInterval, - int RetryTimes, - void (*ErrorCallBack)(int ErrorCode, const char *URL, const char *File), - void (*SuccessCallBack)(const char *URL, const char *File) - ); +int GetFromInternet_SingleFile(const char *URL, + const char *File, + BOOL Append, + int RetryInterval, + int RetryTimes, + void (*ErrorCallBack)(int ErrorCode, const char *URL, const char *File), + void (*SuccessCallBack)(const char *URL, const char *File) + ); int GetFromInternet_Base(const char *URL, const char *File); diff --git a/dynamichosts.c b/dynamichosts.c index 37900b92..a24ba115 100755 --- a/dynamichosts.c +++ b/dynamichosts.c @@ -11,80 +11,80 @@ #include "mmgr.h" static const char *File = NULL; -static RWLock HostsLock; -static volatile HostsContainer *MainDynamicContainer = NULL; +static RWLock HostsLock; +static volatile HostsContainer *MainDynamicContainer = NULL; static int DynamicHosts_Load(void) { - FILE *fp; - char Buffer[320]; - ReadLineStatus Status; - - HostsContainer *TempContainer; - - fp = fopen(File, "r"); - if( fp == NULL ) - { - return -1; - } - - TempContainer = (HostsContainer *)SafeMalloc(sizeof(HostsContainer)); - if( TempContainer == NULL ) - { - fclose(fp); - return -1; - } - - if( HostsContainer_Init(TempContainer) != 0 ) - { - fclose(fp); - - SafeFree(TempContainer); - return -1; - } - - while( TRUE ) - { - Status = ReadLine(fp, Buffer, sizeof(Buffer)); - if( Status == READ_FAILED_OR_END ) + FILE *fp; + char Buffer[320]; + ReadLineStatus Status; + + HostsContainer *TempContainer; + + fp = fopen(File, "r"); + if( fp == NULL ) + { + return -1; + } + + TempContainer = (HostsContainer *)SafeMalloc(sizeof(HostsContainer)); + if( TempContainer == NULL ) + { + fclose(fp); + return -1; + } + + if( HostsContainer_Init(TempContainer) != 0 ) + { + fclose(fp); + + SafeFree(TempContainer); + return -1; + } + + while( TRUE ) + { + Status = ReadLine(fp, Buffer, sizeof(Buffer)); + if( Status == READ_FAILED_OR_END ) { break; } - if( Status == READ_TRUNCATED ) - { - ERRORMSG("Hosts is too long : %s\n", Buffer); - ReadLine_GoToNextLine(fp); - continue; - } + if( Status == READ_TRUNCATED ) + { + ERRORMSG("Hosts is too long : %s\n", Buffer); + ReadLine_GoToNextLine(fp); + continue; + } TempContainer->Load(TempContainer, Buffer); - } + } - RWLock_WrLock(HostsLock); - if( MainDynamicContainer != NULL ) - { - MainDynamicContainer->Free((HostsContainer *)MainDynamicContainer); - SafeFree((void *)MainDynamicContainer); - } - MainDynamicContainer = TempContainer; + RWLock_WrLock(HostsLock); + if( MainDynamicContainer != NULL ) + { + MainDynamicContainer->Free((HostsContainer *)MainDynamicContainer); + SafeFree((void *)MainDynamicContainer); + } + MainDynamicContainer = TempContainer; - RWLock_UnWLock(HostsLock); + RWLock_UnWLock(HostsLock); - INFO("Loading hosts completed.\n"); + INFO("Loading hosts completed.\n"); - fclose(fp); - return 0; + fclose(fp); + return 0; } /* Arguments for updating */ static int HostsRetryInterval; static char *Script = NULL; /* malloced */ -static const char **HostsURLs = NULL; /* malloced */ +static const char **HostsURLs = NULL; /* malloced */ static void GetHostsFromInternet_Failed(int ErrorCode, const char *URL, const char *File1) { - ERRORMSG("Getting Hosts %s failed. Waiting %d second(s) to try again.\n", + ERRORMSG("Getting Hosts %s failed. Waiting %d second(s) to try again.\n", URL, HostsRetryInterval ); @@ -92,12 +92,12 @@ static void GetHostsFromInternet_Failed(int ErrorCode, const char *URL, const ch static void GetHostsFromInternet_Succeed(const char *URL, const char *File1) { - INFO("Hosts %s saved.\n", URL); + INFO("Hosts %s saved.\n", URL); } static void GetHostsFromInternet_Thread(void *Unused1, void *Unused2) { - int DownloadState; + int DownloadState; if( HostsURLs[1] == NULL ) { @@ -138,25 +138,25 @@ static void GetHostsFromInternet_Thread(void *Unused1, void *Unused2) int DynamicHosts_Init(ConfigFileInfo *ConfigInfo) { - StringList *Hosts; - int UpdateInterval; - const char *RawScript; + StringList *Hosts; + int UpdateInterval; + const char *RawScript; - Hosts = ConfigGetStringList(ConfigInfo, "Hosts"); - if( Hosts == NULL ) - { - File = NULL; - return -151; - } + Hosts = ConfigGetStringList(ConfigInfo, "Hosts"); + if( Hosts == NULL ) + { + File = NULL; + return -151; + } - Hosts->TrimAll(Hosts, "\"\t "); + Hosts->TrimAll(Hosts, "\"\t "); HostsURLs = Hosts->ToCharPtrArray(Hosts); - UpdateInterval = ConfigGetInt32(ConfigInfo, "HostsUpdateInterval"); - HostsRetryInterval = ConfigGetInt32(ConfigInfo, "HostsRetryInterval"); + UpdateInterval = ConfigGetInt32(ConfigInfo, "HostsUpdateInterval"); + HostsRetryInterval = ConfigGetInt32(ConfigInfo, "HostsRetryInterval"); - RawScript = ConfigGetRawString(ConfigInfo, "HostsScript"); - if( RawScript != NULL ) + RawScript = ConfigGetRawString(ConfigInfo, "HostsScript"); + if( RawScript != NULL ) { static const int SIZE_OF_PATH_BUFFER = 1024; @@ -178,28 +178,28 @@ int DynamicHosts_Init(ConfigFileInfo *ConfigInfo) Script = NULL; } - RWLock_Init(HostsLock); + RWLock_Init(HostsLock); - File = ConfigGetRawString(ConfigInfo, "HostsDownloadPath"); + File = ConfigGetRawString(ConfigInfo, "HostsDownloadPath"); - if( HostsRetryInterval < 0 ) - { - ERRORMSG("`HostsRetryInterval' is too small (< 0).\n"); - File = NULL; - return -167; - } + if( HostsRetryInterval < 0 ) + { + ERRORMSG("`HostsRetryInterval' is too small (< 0).\n"); + File = NULL; + return -167; + } - INFO("Local hosts file : \"%s\"\n", File); + INFO("Local hosts file : \"%s\"\n", File); - if( FileIsReadable(File) ) - { - INFO("Loading the existing hosts file ...\n"); - DynamicHosts_Load(); - } else { - INFO("Hosts file is unreadable, this may cause some failures.\n"); - } + if( FileIsReadable(File) ) + { + INFO("Loading the existing hosts file ...\n"); + DynamicHosts_Load(); + } else { + INFO("Hosts file is unreadable, this may cause some failures.\n"); + } - if( UpdateInterval <= 0 ) + if( UpdateInterval <= 0 ) { TimedTask_Add(FALSE, TRUE, @@ -218,7 +218,7 @@ int DynamicHosts_Init(ConfigFileInfo *ConfigInfo) TRUE); } - return 0; + return 0; } int DynamicHosts_GetCName(const char *Domain, char *Buffer) diff --git a/filter.c b/filter.c index 45081d90..dc64c80a 100755 --- a/filter.c +++ b/filter.c @@ -9,58 +9,58 @@ #include "domainstatistic.h" #include "rwlock.h" -static Bst *DisabledTypes = NULL; +static Bst *DisabledTypes = NULL; -static StringChunk *DisabledDomain = NULL; -static RWLock DisabledDomainLock; +static StringChunk *DisabledDomain = NULL; +static RWLock DisabledDomainLock; static ConfigFileInfo *CurrConfigInfo = NULL; static int TypeCompare(const int *_1, const int *_2) { - return *_1 - *_2; + return *_1 - *_2; } static int InitBst(Bst **t, int (*CompareFunc)(const void *, const void *)) { - *t = malloc(sizeof(Bst)); - if( *t == NULL ) - { - return -93; - } - - if( Bst_Init(*t, sizeof(int), CompareFunc) != 0 ) - { - return -102; - } - - return 0; + *t = malloc(sizeof(Bst)); + if( *t == NULL ) + { + return -93; + } + + if( Bst_Init(*t, sizeof(int), CompareFunc) != 0 ) + { + return -102; + } + + return 0; } static int LoadDomainsFromList(StringChunk *List, StringList *Domains) { - const char *Str; + const char *Str; - StringListIterator sli; + StringListIterator sli; - if( List == NULL || Domains == NULL ) - { - return 0; - } + if( List == NULL || Domains == NULL ) + { + return 0; + } - if( StringListIterator_Init(&sli, Domains) != 0 ) + if( StringListIterator_Init(&sli, Domains) != 0 ) { return -1; } - Str = sli.Next(&sli); - while( Str != NULL ) - { - StringChunk_Add_Domain(List, Str, NULL, 0); - Str = sli.Next(&sli); - } + Str = sli.Next(&sli); + while( Str != NULL ) + { + StringChunk_Add_Domain(List, Str, NULL, 0); + Str = sli.Next(&sli); + } - return 0; + return 0; } static int FilterDomain_Init(StringChunk **List, ConfigFileInfo *ConfigInfo) @@ -85,8 +85,8 @@ static int FilterDomain_Init(StringChunk **List, ConfigFileInfo *ConfigInfo) static int LoadDomainsFromFile(StringChunk *List, const char *FilePath) { FILE *fp; - ReadLineStatus Status; - char Domain[512]; + ReadLineStatus Status; + char Domain[512]; if( List == NULL || FilePath == NULL ) { @@ -100,17 +100,17 @@ static int LoadDomainsFromFile(StringChunk *List, const char *FilePath) } Status = ReadLine(fp, Domain, sizeof(Domain)); - while( Status != READ_FAILED_OR_END ) - { - if( Status == READ_DONE ) - { - StringChunk_Add_Domain(List, Domain, NULL, 0); - } else { - ReadLine_GoToNextLine(fp); - } - - Status = ReadLine(fp, Domain, sizeof(Domain)); - } + while( Status != READ_FAILED_OR_END ) + { + if( Status == READ_DONE ) + { + StringChunk_Add_Domain(List, Domain, NULL, 0); + } else { + ReadLine_GoToNextLine(fp); + } + + Status = ReadLine(fp, Domain, sizeof(Domain)); + } fclose(fp); @@ -148,43 +148,43 @@ static int FilterDomain_InitFromFile(StringChunk **List, ConfigFileInfo *ConfigI static int FilterType_Init(ConfigFileInfo *ConfigInfo) { - StringList *DisableType_Str = + StringList *DisableType_Str = ConfigGetStringList(ConfigInfo, "DisabledType"); - const char *OneTypePendingToAdd_Str; - int OneTypePendingToAdd; + const char *OneTypePendingToAdd_Str; + int OneTypePendingToAdd; StringListIterator sli; - if( DisableType_Str == NULL ) - { - return 0; - } + if( DisableType_Str == NULL ) + { + return 0; + } - if( InitBst(&DisabledTypes, + if( InitBst(&DisabledTypes, (int (*)(const void *, const void *))TypeCompare ) != 0 ) { return -146; } - if( StringListIterator_Init(&sli, DisableType_Str) != 0 ) + if( StringListIterator_Init(&sli, DisableType_Str) != 0 ) { return -2; } - OneTypePendingToAdd_Str = sli.Next(&sli); - while( OneTypePendingToAdd_Str != NULL ) - { - sscanf(OneTypePendingToAdd_Str, "%d", &OneTypePendingToAdd); - DisabledTypes->Add(DisabledTypes, &OneTypePendingToAdd); + OneTypePendingToAdd_Str = sli.Next(&sli); + while( OneTypePendingToAdd_Str != NULL ) + { + sscanf(OneTypePendingToAdd_Str, "%d", &OneTypePendingToAdd); + DisabledTypes->Add(DisabledTypes, &OneTypePendingToAdd); - OneTypePendingToAdd_Str = sli.Next(&sli); - } + OneTypePendingToAdd_Str = sli.Next(&sli); + } - DisableType_Str->Free(DisableType_Str); + DisableType_Str->Free(DisableType_Str); - return 0; + return 0; } static int DisabledDomain_Init(ConfigFileInfo *ConfigInfo) @@ -230,11 +230,11 @@ int Filter_Init(ConfigFileInfo *ConfigInfo) INFO("Disabled types initialized.\n"); } - RWLock_Init(DisabledDomainLock); + RWLock_Init(DisabledDomainLock); DisabledDomain_Init(ConfigInfo); - return 0; + return 0; } int Filter_Update(void) @@ -249,13 +249,13 @@ int Filter_Update(void) static BOOL IsDisabledType(int Type) { - if( DisabledTypes != NULL && + if( DisabledTypes != NULL && DisabledTypes->Search(DisabledTypes, &Type, NULL) != NULL ) - { - return TRUE; - } else { - return FALSE; - } + { + return TRUE; + } else { + return FALSE; + } } static BOOL IsDisabledDomain(const char *Domain, uint32_t HashValue) diff --git a/goodiplist.c b/goodiplist.c index 35618efb..c128ba1f 100755 --- a/goodiplist.c +++ b/goodiplist.c @@ -8,18 +8,18 @@ #include "logs.h" typedef struct _ListInfo{ - int Interval; - Array List; + int Interval; + Array List; } ListInfo; -static StringChunk *GoodIpList = NULL; +static StringChunk *GoodIpList = NULL; /* The fastest returned */ static struct sockaddr_in *CheckAList(struct sockaddr_in *Ips, int Count) { SocketPuller p; int i; - struct timeval Time = {5, 0}; + struct timeval Time = {5, 0}; struct sockaddr_in **Fastest = NULL; struct sockaddr_in *ret = NULL; @@ -29,29 +29,29 @@ static struct sockaddr_in *CheckAList(struct sockaddr_in *Ips, int Count) return NULL; } - for( i = 0; i != Count; ++i ) + for( i = 0; i != Count; ++i ) { - SOCKET skt; - struct sockaddr *a; + SOCKET skt; + struct sockaddr *a; - skt = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if( skt == INVALID_SOCKET ) - { - continue; - } - SetSocketNonBlock(skt, TRUE); + skt = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if( skt == INVALID_SOCKET ) + { + continue; + } + SetSocketNonBlock(skt, TRUE); - a = (struct sockaddr *)&(Ips[i]); + a = (struct sockaddr *)&(Ips[i]); - if( connect(skt, a, sizeof(struct sockaddr_in)) != 0 && + if( connect(skt, a, sizeof(struct sockaddr_in)) != 0 && FatalErrorDecideding(GET_LAST_ERROR()) != 0 ) - { - CLOSE_SOCKET(skt); - continue; - } + { + CLOSE_SOCKET(skt); + continue; + } - p.Add(&p, skt, &a, sizeof(struct sockaddr *)); + p.Add(&p, skt, &a, sizeof(struct sockaddr *)); } if( p.Select(&p, &Time, (void **)&Fastest, FALSE, TRUE) == INVALID_SOCKET ) @@ -112,41 +112,41 @@ static int ThreadJod(const char *Domain, ListInfo *inf) /* GoodIPList list1 1000 */ static int InitListsAndTimes(ConfigFileInfo *ConfigInfo) { - StringList *l = ConfigGetStringList(ConfigInfo, "GoodIPList"); - StringListIterator sli; + StringList *l = ConfigGetStringList(ConfigInfo, "GoodIPList"); + StringListIterator sli; - const char *Itr = NULL; + const char *Itr = NULL; - if( l == NULL ) - { - return -1; - } + if( l == NULL ) + { + return -1; + } - if( StringListIterator_Init(&sli, l) != 0 ) + if( StringListIterator_Init(&sli, l) != 0 ) { return -2; } - GoodIpList = SafeMalloc(sizeof(StringChunk)); - if( GoodIpList != NULL && StringChunk_Init(GoodIpList, NULL) != 0 ) - { - return -3; - } + GoodIpList = SafeMalloc(sizeof(StringChunk)); + if( GoodIpList != NULL && StringChunk_Init(GoodIpList, NULL) != 0 ) + { + return -3; + } while( (Itr = sli.Next(&sli)) != NULL ) { - ListInfo m = {0, Array_Init_Static(sizeof(struct sockaddr_in))}; - char n[128]; + ListInfo m = {0, Array_Init_Static(sizeof(struct sockaddr_in))}; + char n[128]; - sscanf(Itr, "%127s%d", n, &(m.Interval)); + sscanf(Itr, "%127s%d", n, &(m.Interval)); - if( m.Interval <= 0 ) - { - ERRORMSG("GoodIpList is invalid : %s\n", Itr); - continue; - } + if( m.Interval <= 0 ) + { + ERRORMSG("GoodIpList is invalid : %s\n", Itr); + continue; + } - StringChunk_Add(GoodIpList, n, (const char *)&m, sizeof(ListInfo)); + StringChunk_Add(GoodIpList, n, (const char *)&m, sizeof(ListInfo)); } return 0; @@ -155,46 +155,46 @@ static int InitListsAndTimes(ConfigFileInfo *ConfigInfo) /* GoodIPListAddIP list1 ip:port */ static int AddToLists(ConfigFileInfo *ConfigInfo) { - StringList *l = ConfigGetStringList(ConfigInfo, "GoodIPListAddIP"); - StringListIterator sli; + StringList *l = ConfigGetStringList(ConfigInfo, "GoodIPListAddIP"); + StringListIterator sli; - const char *Itr = NULL; + const char *Itr = NULL; - if( l == NULL ) - { - return -1; - } + if( l == NULL ) + { + return -1; + } - if( StringListIterator_Init(&sli, l) != 0 ) + if( StringListIterator_Init(&sli, l) != 0 ) { return -2; } while( (Itr = sli.Next(&sli)) != NULL ) { - ListInfo *m = NULL; - char n[128], ip_str[LENGTH_OF_IPV4_ADDRESS_ASCII]; - int Port; - struct sockaddr_in ip; + ListInfo *m = NULL; + char n[128], ip_str[LENGTH_OF_IPV4_ADDRESS_ASCII]; + int Port; + struct sockaddr_in ip; - sscanf(Itr, "%127s%*[^0123456789]%15[^:]:%d", n, ip_str, &Port); - ip.sin_port = htons(Port); - ip.sin_family = AF_INET; /* IPv4 only */ + sscanf(Itr, "%127s%*[^0123456789]%15[^:]:%d", n, ip_str, &Port); + ip.sin_port = htons(Port); + ip.sin_family = AF_INET; /* IPv4 only */ - IPv4AddressToNum(ip_str, &(ip.sin_addr)); + IPv4AddressToNum(ip_str, &(ip.sin_addr)); - if( StringChunk_Match_NoWildCard(GoodIpList, + if( StringChunk_Match_NoWildCard(GoodIpList, n, NULL, (void **)&m) == FALSE ) - { - ERRORMSG("GoodIpList is not found : %s\n", Itr); - continue; - } + { + ERRORMSG("GoodIpList is not found : %s\n", Itr); + continue; + } - Array_PushBack(&(m->List), &ip, NULL); + Array_PushBack(&(m->List), &ip, NULL); } return 0; @@ -230,22 +230,22 @@ static int AddTask(void) int GoodIpList_Init(ConfigFileInfo *ConfigInfo) { - if( InitListsAndTimes(ConfigInfo) != 0 ) - { - return -1; - } - - if( AddToLists(ConfigInfo) != 0 ) - { - return -2; - } - - if( AddTask() != 0 ) - { - return -270; - } - - return 0; + if( InitListsAndTimes(ConfigInfo) != 0 ) + { + return -1; + } + + if( AddToLists(ConfigInfo) != 0 ) + { + return -2; + } + + if( AddTask() != 0 ) + { + return -270; + } + + return 0; } const char *GoodIpList_Get(const char *List) diff --git a/hcontext.c b/hcontext.c index d523effb..d4bc4f20 100755 --- a/hcontext.c +++ b/hcontext.c @@ -11,8 +11,8 @@ struct _HostsContextItem{ uint32_t i; /* Query identifier */ uint32_t oi; /* Original identifier */ - char RecursedDomain[256]; - int RecursedHashValue; + char RecursedDomain[256]; + int RecursedHashValue; }; PUBFUNC int HostsContext_Add(HostsContext *c, @@ -86,7 +86,7 @@ PRIFUNC int HostsContext_Swep_Collect(Bst *t, { const int TIME_OUT = 2; /* Seconds */ - time_t Now = time(NULL); + time_t Now = time(NULL); if( Now - Context->t > TIME_OUT ) { @@ -135,12 +135,12 @@ PRIFUNC int HostsContextCompare(const void *_1, const void *_2) const HostsContextItem *One = (HostsContextItem *)_1; const HostsContextItem *Two = (HostsContextItem *)_2; - if( One->i != Two->i ) - { - return (int)(One->i) - (int)(Two->i); - } else { - return One->RecursedHashValue - Two->RecursedHashValue; - } + if( One->i != Two->i ) + { + return (int)(One->i) - (int)(Two->i); + } else { + return One->RecursedHashValue - Two->RecursedHashValue; + } } int HostsContext_Init(HostsContext *c) diff --git a/hosts.c b/hosts.c index c9c50061..89ad958d 100755 --- a/hosts.c +++ b/hosts.c @@ -9,8 +9,8 @@ static BOOL BlockIpv6WhenIpv4Exists = FALSE; -static SOCKET IncomeSocket; -static Address_Type IncomeAddress; +static SOCKET IncomeSocket; +static Address_Type IncomeAddress; BOOL Hosts_TypeExisting(const char *Domain, HostsRecordType Type) { @@ -112,28 +112,28 @@ int Hosts_Get(IHeader *Header, int BufferLength) static int Hosts_SocketLoop(void *Unused) { - static HostsContext Context; - static SocketPuller Puller; + static HostsContext Context; + static SocketPuller Puller; - static SOCKET OutcomeSocket; - static Address_Type OutcomeAddress; + static SOCKET OutcomeSocket; + static Address_Type OutcomeAddress; - static const struct timeval LongTime = {3600, 0}; - static const struct timeval ShortTime = {10, 0}; + static const struct timeval LongTime = {3600, 0}; + static const struct timeval ShortTime = {10, 0}; - struct timeval TimeLimit = LongTime; + struct timeval TimeLimit = LongTime; - #define LEFT_LENGTH_SL (sizeof(RequestBuffer) - sizeof(IHeader)) - static char RequestBuffer[2048]; - IHeader *Header = (IHeader *)RequestBuffer; - char *RequestEntity = RequestBuffer + sizeof(IHeader); + #define LEFT_LENGTH_SL (sizeof(RequestBuffer) - sizeof(IHeader)) + static char RequestBuffer[2048]; + IHeader *Header = (IHeader *)RequestBuffer; + char *RequestEntity = RequestBuffer + sizeof(IHeader); - OutcomeSocket = TryBindLocal(Ipv6_Aviliable(), 10300, &OutcomeAddress); + OutcomeSocket = TryBindLocal(Ipv6_Aviliable(), 10300, &OutcomeAddress); - if( OutcomeSocket == INVALID_SOCKET ) - { - return -416; - } + if( OutcomeSocket == INVALID_SOCKET ) + { + return -416; + } if( SocketPuller_Init(&Puller) != 0 ) { @@ -150,12 +150,12 @@ static int Hosts_SocketLoop(void *Unused) srand(time(NULL)); - while( TRUE ) - { - SOCKET Pulled; + while( TRUE ) + { + SOCKET Pulled; - Pulled = Puller.Select(&Puller, &TimeLimit, NULL, TRUE, FALSE); - if( Pulled == INVALID_SOCKET ) + Pulled = Puller.Select(&Puller, &TimeLimit, NULL, TRUE, FALSE); + if( Pulled == INVALID_SOCKET ) { TimeLimit = LongTime; Context.Swep(&Context); @@ -257,9 +257,9 @@ static int Hosts_SocketLoop(void *Unused) ShowNormalMessage(NewHeader, 'H'); } else {} - } + } - return 0; + return 0; } int Hosts_Init(ConfigFileInfo *ConfigInfo) diff --git a/hostscontainer.c b/hostscontainer.c index 5ab32036..71973d1c 100755 --- a/hostscontainer.c +++ b/hostscontainer.c @@ -13,68 +13,68 @@ struct _TableNode{ PRIFUNC HostsRecordType HostsContainer_DetermineType(const char *IPOrCName) { - if( IPOrCName == NULL ) - { - return HOSTS_TYPE_UNKNOWN; - } - - /* Good IP List */ - if( *IPOrCName == '<' && IPOrCName[strlen(IPOrCName) - 1] == '>' ) - { - return HOSTS_TYPE_GOOD_IP_LIST; - } - - /* A host IPOrCName started with "@@ " is excluded */ - if( *IPOrCName == '@' && *(IPOrCName + 1) == '@' ) - { - return HOSTS_TYPE_EXCLUEDE; - } - - if( isxdigit(*IPOrCName) ) - { - const char *Itr; - /* Check if it is IPv6 */ - if( strchr(IPOrCName, ':') != NULL ) - { - return HOSTS_TYPE_AAAA; - } - - /* Check if it is CNAME */ - for(Itr = IPOrCName; *Itr != '\0'; ++Itr) - { - if( isalpha(*Itr) || *Itr == '-' ) - { - return HOSTS_TYPE_CNAME; - } - } - - for(Itr = IPOrCName; *Itr != '\0'; ++Itr) - { - if( isdigit(*Itr) || *Itr == '.' ) - { - return HOSTS_TYPE_A; - } - } - - return HOSTS_TYPE_UNKNOWN; - - } else { - - if( *IPOrCName == ':' ) - { - return HOSTS_TYPE_AAAA; - } - - for(; *IPOrCName != '\0'; ++IPOrCName) - { - if( !isalnum(*IPOrCName) && *IPOrCName != '-' && *IPOrCName != '.' ) - { - return HOSTS_TYPE_UNKNOWN; - } - } - - return HOSTS_TYPE_CNAME; - } + if( IPOrCName == NULL ) + { + return HOSTS_TYPE_UNKNOWN; + } + + /* Good IP List */ + if( *IPOrCName == '<' && IPOrCName[strlen(IPOrCName) - 1] == '>' ) + { + return HOSTS_TYPE_GOOD_IP_LIST; + } + + /* A host IPOrCName started with "@@ " is excluded */ + if( *IPOrCName == '@' && *(IPOrCName + 1) == '@' ) + { + return HOSTS_TYPE_EXCLUEDE; + } + + if( isxdigit(*IPOrCName) ) + { + const char *Itr; + /* Check if it is IPv6 */ + if( strchr(IPOrCName, ':') != NULL ) + { + return HOSTS_TYPE_AAAA; + } + + /* Check if it is CNAME */ + for(Itr = IPOrCName; *Itr != '\0'; ++Itr) + { + if( isalpha(*Itr) || *Itr == '-' ) + { + return HOSTS_TYPE_CNAME; + } + } + + for(Itr = IPOrCName; *Itr != '\0'; ++Itr) + { + if( isdigit(*Itr) || *Itr == '.' ) + { + return HOSTS_TYPE_A; + } + } + + return HOSTS_TYPE_UNKNOWN; + + } else { + + if( *IPOrCName == ':' ) + { + return HOSTS_TYPE_AAAA; + } + + for(; *IPOrCName != '\0'; ++IPOrCName) + { + if( !isalnum(*IPOrCName) && *IPOrCName != '-' && *IPOrCName != '.' ) + { + return HOSTS_TYPE_UNKNOWN; + } + } + + return HOSTS_TYPE_CNAME; + } } /* @@ -95,15 +95,15 @@ PUBFUNC const void *HostsContainer_Find(HostsContainer *Container, { int Number = 1; - const TableNode **Matched = NULL; - const TableNode *IP = NULL; + const TableNode **Matched = NULL; + const TableNode *IP = NULL; - if( !StringChunk_Match(&(Container->Mappings), Name, NULL, (void **)&Matched) ) - { + if( !StringChunk_Match(&(Container->Mappings), Name, NULL, (void **)&Matched) ) + { return NULL; - } + } - if( Matched != NULL ) + if( Matched != NULL ) { IP = *Matched; } @@ -148,15 +148,15 @@ PRIFUNC const void *HostsContainer_FindExist(HostsContainer *Container, const char *Name ) { - const TableNode **Matched = NULL; - const TableNode *IP = NULL; + const TableNode **Matched = NULL; + const TableNode *IP = NULL; - if( !StringChunk_Match_Exacly(&(Container->Mappings), Name, NULL, (void **)&Matched) ) - { + if( !StringChunk_Match_Exacly(&(Container->Mappings), Name, NULL, (void **)&Matched) ) + { return NULL; - } + } - if( Matched != NULL ) + if( Matched != NULL ) { IP = *Matched; } @@ -241,9 +241,9 @@ PRIFUNC int HostsContainer_AddIPV6(HostsContainer *Container, const char *Domain ) { - char NumericIP[16]; + char NumericIP[16]; - IPv6AddressToNum(IPOrCName, NumericIP); + IPv6AddressToNum(IPOrCName, NumericIP); return HostsContainer_AddNode(Container, Domain, @@ -258,9 +258,9 @@ PRIFUNC int HostsContainer_AddIPV4(HostsContainer *Container, const char *Domain ) { - char NumericIP[4]; + char NumericIP[4]; - IPv4AddressToNum(IPOrCName, NumericIP); + IPv4AddressToNum(IPOrCName, NumericIP); return HostsContainer_AddNode(Container, Domain, @@ -288,7 +288,7 @@ PRIFUNC int HostsContainer_AddGoodIpList(HostsContainer *Container, const char *Domain ) { - char Trimed[128]; + char Trimed[128]; sscanf(ListName, "<%127[^>]", Trimed); @@ -317,102 +317,102 @@ PRIFUNC HostsRecordType HostsContainer_Add(HostsContainer *Container, const char *Domain ) { - switch( HostsContainer_DetermineType(IPOrCName) ) - { - case HOSTS_TYPE_AAAA: - if( HostsContainer_AddIPV6(Container, IPOrCName, Domain) != 0) - { - return HOSTS_TYPE_UNKNOWN; - } else { - return HOSTS_TYPE_AAAA; - } - break; - - case HOSTS_TYPE_A: - if( HostsContainer_AddIPV4(Container, IPOrCName, Domain) != 0 ) - { - return HOSTS_TYPE_UNKNOWN; - } else { - return HOSTS_TYPE_A; - } - break; - - case HOSTS_TYPE_CNAME: - if( HostsContainer_AddCName(Container, IPOrCName, Domain) != 0 ) - { - return HOSTS_TYPE_UNKNOWN; - } else { - return HOSTS_TYPE_CNAME; - } - break; - - case HOSTS_TYPE_EXCLUEDE: - if( HostsContainer_AddExcluded(Container, Domain) != 0 ) - { - return HOSTS_TYPE_UNKNOWN; - } else { - return HOSTS_TYPE_EXCLUEDE; - } - break; - - case HOSTS_TYPE_GOOD_IP_LIST: - if( HostsContainer_AddGoodIpList(Container, IPOrCName, Domain) != 0 ) - { - return HOSTS_TYPE_UNKNOWN; - } else { - return HOSTS_TYPE_GOOD_IP_LIST; - } - break; - - default: - INFO("Unrecognisable host : %s %s\n", IPOrCName, Domain); - return HOSTS_TYPE_UNKNOWN; - break; - } + switch( HostsContainer_DetermineType(IPOrCName) ) + { + case HOSTS_TYPE_AAAA: + if( HostsContainer_AddIPV6(Container, IPOrCName, Domain) != 0) + { + return HOSTS_TYPE_UNKNOWN; + } else { + return HOSTS_TYPE_AAAA; + } + break; + + case HOSTS_TYPE_A: + if( HostsContainer_AddIPV4(Container, IPOrCName, Domain) != 0 ) + { + return HOSTS_TYPE_UNKNOWN; + } else { + return HOSTS_TYPE_A; + } + break; + + case HOSTS_TYPE_CNAME: + if( HostsContainer_AddCName(Container, IPOrCName, Domain) != 0 ) + { + return HOSTS_TYPE_UNKNOWN; + } else { + return HOSTS_TYPE_CNAME; + } + break; + + case HOSTS_TYPE_EXCLUEDE: + if( HostsContainer_AddExcluded(Container, Domain) != 0 ) + { + return HOSTS_TYPE_UNKNOWN; + } else { + return HOSTS_TYPE_EXCLUEDE; + } + break; + + case HOSTS_TYPE_GOOD_IP_LIST: + if( HostsContainer_AddGoodIpList(Container, IPOrCName, Domain) != 0 ) + { + return HOSTS_TYPE_UNKNOWN; + } else { + return HOSTS_TYPE_GOOD_IP_LIST; + } + break; + + default: + INFO("Unrecognisable host : %s %s\n", IPOrCName, Domain); + return HOSTS_TYPE_UNKNOWN; + break; + } } PUBFUNC HostsRecordType HostsContainer_Load(HostsContainer *Container, const char *MetaLine ) { - char IPOrCName[DOMAIN_NAME_LENGTH_MAX + 1]; - char Domain[DOMAIN_NAME_LENGTH_MAX + 1]; + char IPOrCName[DOMAIN_NAME_LENGTH_MAX + 1]; + char Domain[DOMAIN_NAME_LENGTH_MAX + 1]; - if( sscanf(MetaLine, + if( sscanf(MetaLine, "%" STRINGIZINGINT(DOMAIN_NAME_LENGTH_MAX) "s%" STRINGIZINGINT(DOMAIN_NAME_LENGTH_MAX) "s", IPOrCName, Domain ) != 2 ) { - INFO("Unrecognisable host : %s, it may be too long.\n", MetaLine); - return HOSTS_TYPE_UNKNOWN; + INFO("Unrecognisable host : %s, it may be too long.\n", MetaLine); + return HOSTS_TYPE_UNKNOWN; } - return HostsContainer_Add(Container, IPOrCName, Domain); + return HostsContainer_Add(Container, IPOrCName, Domain); } PUBFUNC void HostsContainer_Free(HostsContainer *Container) { - StringChunk_Free(&(Container->Mappings), TRUE); - Container->Table.Free(&(Container->Table)); + StringChunk_Free(&(Container->Mappings), TRUE); + Container->Table.Free(&(Container->Table)); } int HostsContainer_Init(HostsContainer *Container) { - if( StringChunk_Init(&(Container->Mappings), NULL) != 0 ) - { - return -2; - } + if( StringChunk_Init(&(Container->Mappings), NULL) != 0 ) + { + return -2; + } - if( StableBuffer_Init(&(Container->Table)) != 0 ) - { - return -6; - } + if( StableBuffer_Init(&(Container->Table)) != 0 ) + { + return -6; + } - Container->Load = HostsContainer_Load; - Container->Find = HostsContainer_Find; - Container->Free = HostsContainer_Free; + Container->Load = HostsContainer_Load; + Container->Find = HostsContainer_Find; + Container->Free = HostsContainer_Free; - return 0; + return 0; } diff --git a/hostscontainer.h b/hostscontainer.h index cdca091d..08c00652 100755 --- a/hostscontainer.h +++ b/hostscontainer.h @@ -7,13 +7,13 @@ #include "oo.h" typedef enum _HostsRecordType{ - HOSTS_TYPE_TOO_LONG = -1, - HOSTS_TYPE_UNKNOWN = 0, - HOSTS_TYPE_A = 1 << 1, - HOSTS_TYPE_AAAA = 1 << 2, - HOSTS_TYPE_CNAME = 1 << 3, - HOSTS_TYPE_EXCLUEDE = 1 << 4, - HOSTS_TYPE_GOOD_IP_LIST = 1 << 5, + HOSTS_TYPE_TOO_LONG = -1, + HOSTS_TYPE_UNKNOWN = 0, + HOSTS_TYPE_A = 1 << 1, + HOSTS_TYPE_AAAA = 1 << 2, + HOSTS_TYPE_CNAME = 1 << 3, + HOSTS_TYPE_EXCLUEDE = 1 << 4, + HOSTS_TYPE_GOOD_IP_LIST = 1 << 5, } HostsRecordType; @@ -27,10 +27,10 @@ typedef int (*HostsFindFunc)(int Number, /* Start with 1 */ ); struct _HostsContainer{ - PRIMEMB StringChunk Mappings; - PRIMEMB StableBuffer Table; + PRIMEMB StringChunk Mappings; + PRIMEMB StableBuffer Table; - PUBMEMB HostsRecordType (*Load)(HostsContainer *Container, + PUBMEMB HostsRecordType (*Load)(HostsContainer *Container, const char *MetaLine ); diff --git a/hostsutils.c b/hostsutils.c index 13374cae..8b19f917 100755 --- a/hostsutils.c +++ b/hostsutils.c @@ -124,9 +124,9 @@ HostsUtilsTryResult HostsUtils_Try(IHeader *Header, HostsContainer *Container ) { - char *RequestEntity = (char *)(Header + 1); - const char *MatchState; - HostsRecordType Type; + char *RequestEntity = (char *)(Header + 1); + const char *MatchState; + HostsRecordType Type; if( Header->Type != DNS_TYPE_CNAME && HostsUtils_TypeExisting(Container, Header->Domain, HOSTS_TYPE_CNAME) @@ -183,8 +183,8 @@ HostsUtilsTryResult HostsUtils_Try(IHeader *Header, break; } - if( MatchState != NULL ) - { + if( MatchState != NULL ) + { DnsGenerator g; char *HereToGenerate = RequestEntity + Header->EntityLength; @@ -249,9 +249,9 @@ HostsUtilsTryResult HostsUtils_Try(IHeader *Header, IHeader_SendBack(Header); return HOSTSUTILS_TRY_OK; - } else { - return HOSTSUTILS_TRY_NONE; - } + } else { + return HOSTSUTILS_TRY_NONE; + } } int HostsUtils_Query(SOCKET Socket, /* Both for sending and receiving */ @@ -274,9 +274,9 @@ int HostsUtils_Query(SOCKET Socket, /* Both for sending and receiving */ IHeader *Header = (IHeader *)RequestBuffer; char *RequestEntity = RequestBuffer + sizeof(IHeader); - DnsGenerator g; + DnsGenerator g; - if( DnsGenerator_Init(&g, + if( DnsGenerator_Init(&g, RequestEntity, sizeof(RequestBuffer) - sizeof(IHeader), DNSHeader, diff --git a/iheader.h b/iheader.h index 696a2f8f..83a30d18 100755 --- a/iheader.h +++ b/iheader.h @@ -7,21 +7,21 @@ typedef struct _IHeader IHeader; struct _IHeader{ - int32_t _Pad; /* Must be 0 */ + int32_t _Pad; /* Must be 0 */ - Address_Type BackAddress; - SOCKET SendBackSocket; + Address_Type BackAddress; + SOCKET SendBackSocket; - char Domain[256]; - uint32_t HashValue; - DNSRecordType Type; + char Domain[256]; + uint32_t HashValue; + DNSRecordType Type; - BOOL ReturnHeader; - BOOL EDNSEnabled; + BOOL ReturnHeader; + BOOL EDNSEnabled; - int EntityLength; + int EntityLength; - char Agent[ROUND_UP(LENGTH_OF_IPV6_ADDRESS_ASCII + 1, + char Agent[ROUND_UP(LENGTH_OF_IPV6_ADDRESS_ASCII + 1, sizeof(void *) ) ]; diff --git a/ipchunk.c b/ipchunk.c index af0731c3..13c78d29 100755 --- a/ipchunk.c +++ b/ipchunk.c @@ -4,40 +4,40 @@ static int Compare(IpElement *_1, IpElement *_2) { - if( _1->IpLength != _2->IpLength ) - { - return _1->IpLength - _2->IpLength; - } else { - if( _1->IpLength == 4 ) - { - return _1->Ip.Ipv4 - _2->Ip.Ipv4; - } else { - return memcmp(_1->Ip.Ipv6, _2->Ip.Ipv6, _1->IpLength); - } - } + if( _1->IpLength != _2->IpLength ) + { + return _1->IpLength - _2->IpLength; + } else { + if( _1->IpLength == 4 ) + { + return _1->Ip.Ipv4 - _2->Ip.Ipv4; + } else { + return memcmp(_1->Ip.Ipv6, _2->Ip.Ipv6, _1->IpLength); + } + } } int IpChunk_Init(IpChunk *ic) { - IpElement Root; - Root.IpLength = 10; /* 4 < 10 < 16 */ + IpElement Root; + Root.IpLength = 10; /* 4 < 10 < 16 */ - if( Bst_Init(&(ic->Chunk), sizeof(IpElement), (CompareFunc)Compare) != 0 ) - { - return -1; - } + if( Bst_Init(&(ic->Chunk), sizeof(IpElement), (CompareFunc)Compare) != 0 ) + { + return -1; + } - if( StableBuffer_Init(&(ic->Datas)) != 0 ) - { - return -1; - } + if( StableBuffer_Init(&(ic->Datas)) != 0 ) + { + return -1; + } - if( ic->Chunk.Add(&(ic->Chunk), &Root) == NULL ) + if( ic->Chunk.Add(&(ic->Chunk), &Root) == NULL ) { return -37; } - return 0; + return 0; } int IpChunk_Add(IpChunk *ic, @@ -49,18 +49,18 @@ int IpChunk_Add(IpChunk *ic, { StableBuffer *sb = &(ic->Datas); - IpElement New; - New.IpLength = 4; - New.Ip.Ipv4 = Ip; - New.Type = Type; - New.Data = NULL; + IpElement New; + New.IpLength = 4; + New.Ip.Ipv4 = Ip; + New.Type = Type; + New.Data = NULL; - if( Data != NULL ) - { - New.Data = sb->Add(sb, Data, DataLength, TRUE); - } + if( Data != NULL ) + { + New.Data = sb->Add(sb, Data, DataLength, TRUE); + } - return ic->Chunk.Add(&(ic->Chunk), &New) == NULL; + return ic->Chunk.Add(&(ic->Chunk), &New) == NULL; } int IpChunk_AddFromString(IpChunk *ic, @@ -81,18 +81,18 @@ int IpChunk_Add6(IpChunk *ic, const char *Ipv6, int Type, const char *Data, uint { StableBuffer *sb = &(ic->Datas); - IpElement New; - New.IpLength = 16; - memcpy(New.Ip.Ipv6, Ipv6, 16); - New.Type = Type; - New.Data = NULL; + IpElement New; + New.IpLength = 16; + memcpy(New.Ip.Ipv6, Ipv6, 16); + New.Type = Type; + New.Data = NULL; - if( Data != NULL ) - { - New.Data = sb->Add(sb, Data, DataLength, TRUE); - } + if( Data != NULL ) + { + New.Data = sb->Add(sb, Data, DataLength, TRUE); + } - return ic->Chunk.Add(&(ic->Chunk), &New) == NULL; + return ic->Chunk.Add(&(ic->Chunk), &New) == NULL; } int IpChunk_Add6FromString(IpChunk *ic, @@ -102,7 +102,7 @@ int IpChunk_Add6FromString(IpChunk *ic, uint32_t DataLength ) { - char IpNum[16]; + char IpNum[16]; IPv6AddressToNum(Ip, IpNum); @@ -126,25 +126,25 @@ int IpChunk_AddAnyFromString(IpChunk *ic, BOOL IpChunk_Find(IpChunk *ic, uint32_t Ip, int *Type, const char **Data) { - IpElement Key; - const IpElement *Result; + IpElement Key; + const IpElement *Result; - if( ic == NULL ) - { - return FALSE; - } + if( ic == NULL ) + { + return FALSE; + } - Key.IpLength = 4; - Key.Ip.Ipv4 = Ip; - Key.Type = 0; - Key.Data = NULL; + Key.IpLength = 4; + Key.Ip.Ipv4 = Ip; + Key.Type = 0; + Key.Data = NULL; - Result = ic->Chunk.Search(&(ic->Chunk), &Key, NULL); + Result = ic->Chunk.Search(&(ic->Chunk), &Key, NULL); - if( Result == NULL ) - { - return FALSE; - } else { + if( Result == NULL ) + { + return FALSE; + } else { if( Type != NULL ) { *Type = Result->Type; @@ -155,31 +155,31 @@ BOOL IpChunk_Find(IpChunk *ic, uint32_t Ip, int *Type, const char **Data) *Data = Result->Data; } - return TRUE; - } + return TRUE; + } } BOOL IpChunk_Find6(IpChunk *ic, const char *Ipv6, int *Type, const char **Data) { - IpElement Key; - const IpElement *Result; + IpElement Key; + const IpElement *Result; - if( ic == NULL ) - { - return FALSE; - } + if( ic == NULL ) + { + return FALSE; + } - Key.IpLength = 16; - memcpy(Key.Ip.Ipv6, Ipv6, 16); - Key.Type = 0; - Key.Data = NULL; + Key.IpLength = 16; + memcpy(Key.Ip.Ipv6, Ipv6, 16); + Key.Type = 0; + Key.Data = NULL; - Result = ic->Chunk.Search(&(ic->Chunk), &Key, NULL); + Result = ic->Chunk.Search(&(ic->Chunk), &Key, NULL); - if( Result == NULL ) - { - return FALSE; - } else { + if( Result == NULL ) + { + return FALSE; + } else { if( Type != NULL ) { *Type = Result->Type; @@ -190,6 +190,6 @@ BOOL IpChunk_Find6(IpChunk *ic, const char *Ipv6, int *Type, const char **Data) *Data = Result->Data; } - return TRUE; - } + return TRUE; + } } diff --git a/ipchunk.h b/ipchunk.h index 512dde54..b251e771 100755 --- a/ipchunk.h +++ b/ipchunk.h @@ -6,18 +6,18 @@ #include "common.h" typedef struct _IpElement { - int IpLength; - union { - uint32_t Ipv4; - char Ipv6[16]; - } Ip; - int Type; - void *Data; + int IpLength; + union { + uint32_t Ipv4; + char Ipv6[16]; + } Ip; + int Type; + void *Data; } IpElement; typedef struct _IpChunk{ - Bst Chunk; - StableBuffer Datas; + Bst Chunk; + StableBuffer Datas; } IpChunk; int IpChunk_Init(IpChunk *ic); diff --git a/ipmisc.c b/ipmisc.c index a43d843d..4411f6bb 100755 --- a/ipmisc.c +++ b/ipmisc.c @@ -19,7 +19,7 @@ static int IPMisc_AddSubstituteFromString(IPMisc *m, { if( strchr(Ip, ':') != NULL ) { /* IPv6 */ - char IpSubstituter[16]; + char IpSubstituter[16]; IPv6AddressToNum(Substituter, IpSubstituter); @@ -31,7 +31,7 @@ static int IPMisc_AddSubstituteFromString(IPMisc *m, ); } else { /* IPv4 */ - char IpSubstituter[4]; + char IpSubstituter[4]; IPv4AddressToNum(Substituter, IpSubstituter); diff --git a/linkedqueue.h b/linkedqueue.h index 08a7ae33..4bf11c72 100755 --- a/linkedqueue.h +++ b/linkedqueue.h @@ -6,7 +6,7 @@ typedef struct _ListHead ListHead; struct _ListHead{; - ListHead *Next; + ListHead *Next; }; typedef struct _LinkedQueue LinkedQueue; diff --git a/logs.c b/logs.c index b3613af7..0a0f6c76 100755 --- a/logs.c +++ b/logs.c @@ -7,14 +7,14 @@ #define MAX_PATH_BUFFER 256 -static BOOL PrintConsole = FALSE; -static BOOL DebugOn = FALSE; +static BOOL PrintConsole = FALSE; +static BOOL DebugOn = FALSE; -static FILE *LogFile = NULL; +static FILE *LogFile = NULL; -static int ThresholdLength = 0; -static int CurrentLength = 0; -static char FilePath[MAX_PATH_BUFFER]; +static int ThresholdLength = 0; +static int CurrentLength = 0; +static char FilePath[MAX_PATH_BUFFER]; static EFFECTIVE_LOCK PrintLock; @@ -25,12 +25,12 @@ int Log_Init(ConfigFileInfo *ConfigInfo, BOOL PrintScreen, BOOL Debug) EFFECTIVE_LOCK_INIT(PrintLock); - if( ConfigGetBoolean(ConfigInfo, "LogOn") == FALSE ) - { - return 0; - } + if( ConfigGetBoolean(ConfigInfo, "LogOn") == FALSE ) + { + return 0; + } - if( snprintf(FilePath, + if( snprintf(FilePath, sizeof(FilePath), "%s%cdnsforwarder.log", ConfigGetRawString(ConfigInfo, "LogFileFolder"), @@ -42,35 +42,35 @@ int Log_Init(ConfigFileInfo *ConfigInfo, BOOL PrintScreen, BOOL Debug) return -36; } - LogFile = fopen(FilePath, "r+"); - if( LogFile == NULL ) - { - /* File does not exist */ - LogFile = fopen(FilePath, "w"); - if( LogFile == NULL ) + LogFile = fopen(FilePath, "r+"); + if( LogFile == NULL ) + { + /* File does not exist */ + LogFile = fopen(FilePath, "w"); + if( LogFile == NULL ) { printf("ERROR: Log file %s is unwritable. Try run `dnsforwarder -p'.\n", FilePath); return -44; } - CurrentLength = 0; - } else { - fseek(LogFile, 0, SEEK_END); - CurrentLength = ftell(LogFile); - } + CurrentLength = 0; + } else { + fseek(LogFile, 0, SEEK_END); + CurrentLength = ftell(LogFile); + } - ThresholdLength = ConfigGetInt32(ConfigInfo, "LogFileThresholdLength"); - if( ThresholdLength <= 0 ) + ThresholdLength = ConfigGetInt32(ConfigInfo, "LogFileThresholdLength"); + if( ThresholdLength <= 0 ) { return -60; } - return 0; + return 0; } BOOL Log_Inited(void) { - return LogFile != NULL || PrintConsole; + return LogFile != NULL || PrintConsole; } BOOL Log_DebugOn(void) @@ -82,8 +82,8 @@ static void CheckLength(void) { static int CurrentNumber = 0; - if( CurrentLength >= ThresholdLength ) - { + if( CurrentLength >= ThresholdLength ) + { char FileRenamed[MAX_PATH_BUFFER + 8]; fclose(LogFile); @@ -123,26 +123,26 @@ static void CheckLength(void) break; } } - } + } } void Log_Print(const char *Type, const char *format, ...) { - va_list ap; - char DateAndTime[32]; + va_list ap; + char DateAndTime[32]; - if( !Log_Inited() ) + if( !Log_Inited() ) { return; } GetCurDateAndTime(DateAndTime, sizeof(DateAndTime)); - va_start(ap, format); + va_start(ap, format); - EFFECTIVE_LOCK_GET(PrintLock); - if( LogFile != NULL ) - { + EFFECTIVE_LOCK_GET(PrintLock); + if( LogFile != NULL ) + { CheckLength(); CurrentLength += fprintf(LogFile, @@ -155,9 +155,9 @@ void Log_Print(const char *Type, const char *format, ...) fflush(LogFile); va_start(ap, format); - } + } - if( PrintConsole ) + if( PrintConsole ) { printf(Type == NULL ? "%s " : "%s [%s] ", DateAndTime, @@ -166,9 +166,9 @@ void Log_Print(const char *Type, const char *format, ...) vprintf(format, ap); } - EFFECTIVE_LOCK_RELEASE(PrintLock); + EFFECTIVE_LOCK_RELEASE(PrintLock); - va_end(ap); + va_end(ap); } void ShowRefusingMessage(IHeader *h, const char *Message) @@ -202,7 +202,7 @@ void ShowErrorMessage(IHeader *h, char Protocol) ErrorNum = GET_LAST_ERROR(); ErrorMessage[0] ='\0'; - GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); + GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); Log_Print(NULL, "[%c][%s][%s][%s] An error occured : %d : %s .\n", @@ -223,8 +223,8 @@ void ShowNormalMessage(IHeader *h, char Protocol) char *Package = (char *)(h + 1); char InfoBuffer[1024]; - InfoBuffer[0] = '\0'; - GetAllAnswers(Package, h->EntityLength, InfoBuffer, sizeof(InfoBuffer)); + InfoBuffer[0] = '\0'; + GetAllAnswers(Package, h->EntityLength, InfoBuffer, sizeof(InfoBuffer)); Log_Print(NULL, "[%c][%s][%s][%s] : %d bytes\n%s", @@ -245,8 +245,8 @@ void ShowBlockedMessage(IHeader *h, const char *Message) char *Package = (char *)(h + 1); char InfoBuffer[1024]; - InfoBuffer[0] = '\0'; - GetAllAnswers(Package, h->EntityLength, InfoBuffer, sizeof(InfoBuffer)); + InfoBuffer[0] = '\0'; + GetAllAnswers(Package, h->EntityLength, InfoBuffer, sizeof(InfoBuffer)); Log_Print(NULL, "[B][%s][%s] %s :\n%s", @@ -260,10 +260,10 @@ void ShowBlockedMessage(IHeader *h, const char *Message) void ShowSocketError(const char *Prompts, int ErrorNum) { - if( PRINTON ) - { - char ErrorMessage[320]; - GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); - ERRORMSG("%s : %d : %s\n", Prompts, ErrorNum, ErrorMessage); - } + if( PRINTON ) + { + char ErrorMessage[320]; + GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); + ERRORMSG("%s : %d : %s\n", Prompts, ErrorNum, ErrorMessage); + } } diff --git a/logs.h b/logs.h index 429b66e5..e35f420a 100755 --- a/logs.h +++ b/logs.h @@ -5,9 +5,9 @@ #include "common.h" #include "iheader.h" -#define PRINTON Log_Inited() +#define PRINTON Log_Inited() -#define DEBUGSECTION if( PRINTON && Log_DebugOn() ) +#define DEBUGSECTION if( PRINTON && Log_DebugOn() ) int Log_Init(ConfigFileInfo *ConfigInfo, BOOL PrintScreen, BOOL Debug); @@ -17,10 +17,10 @@ BOOL Log_DebugOn(void); void Log_Print(const char *Type, const char *format, ...); -#define WARNING(...) Log_Print("WARN", __VA_ARGS__) -#define INFO(...) Log_Print("INFO", __VA_ARGS__) -#define ERRORMSG(...) Log_Print("ERROR", __VA_ARGS__) -#define DEBUG(...) DEBUGSECTION \ +#define WARNING(...) Log_Print("WARN", __VA_ARGS__) +#define INFO(...) Log_Print("INFO", __VA_ARGS__) +#define ERRORMSG(...) Log_Print("ERROR", __VA_ARGS__) +#define DEBUG(...) DEBUGSECTION \ Log_Print("DEBUG", __VA_ARGS__); void ShowRefusingMessage(IHeader *h, const char *Message); diff --git a/main.c b/main.c index 763a18a4..a58cabb4 100755 --- a/main.c +++ b/main.c @@ -4,13 +4,13 @@ #include /* exit() */ #ifndef NODOWNLOAD - #ifndef WIN32 - #include - #include - #ifdef DOWNLOAD_LIBCURL - #include - #endif /* DOWNLOAD_LIBCURL */ - #endif /* WIN32 */ + #ifndef WIN32 + #include + #include + #ifdef DOWNLOAD_LIBCURL + #include + #endif /* DOWNLOAD_LIBCURL */ + #endif /* WIN32 */ #endif /* NODOWNLOAD */ #include "common.h" @@ -24,27 +24,27 @@ #define VERSION__ "6.2.0" -static char *ConfigFile; -static BOOL DeamonMode; +static char *ConfigFile; +static BOOL DeamonMode; static BOOL ShowMessages = TRUE; static BOOL DebugOn = FALSE; -static ConfigFileInfo ConfigInfo; +static ConfigFileInfo ConfigInfo; static int EnvironmentInit(void) { - VType TmpTypeDescriptor; - char TmpStr[1024]; + VType TmpTypeDescriptor; + char TmpStr[1024]; - /* Setting env */ - GetFileDirectory(TmpStr); - strcat(TmpStr, PATH_SLASH_STR); + /* Setting env */ + GetFileDirectory(TmpStr); + strcat(TmpStr, PATH_SLASH_STR); - SetProgramEnvironment("PROGRAMDIRECTORY", TmpStr); + SetProgramEnvironment("PROGRAMDIRECTORY", TmpStr); - strncpy(TmpStr, ConfigFile, sizeof(TmpStr)); - TmpStr[sizeof(TmpStr) - 1] = '\0'; + strncpy(TmpStr, ConfigFile, sizeof(TmpStr)); + TmpStr[sizeof(TmpStr) - 1] = '\0'; if( GetPathPart(TmpStr) == NULL ) { @@ -52,10 +52,10 @@ static int EnvironmentInit(void) TmpStr[sizeof(TmpStr) - 1] = '\0'; } - SetProgramEnvironment("CONFIGFILEDIRECTORY", TmpStr); + SetProgramEnvironment("CONFIGFILEDIRECTORY", TmpStr); /* Initializing configure options */ - ConfigInitInfo(&ConfigInfo); + ConfigInitInfo(&ConfigInfo); TmpTypeDescriptor.boolean = FALSE; ConfigAddOption(&ConfigInfo, "LogOn", STRATEGY_DEFAULT, TYPE_BOOLEAN, TmpTypeDescriptor); @@ -63,8 +63,8 @@ static int EnvironmentInit(void) TmpTypeDescriptor.INT32 = 102400; ConfigAddOption(&ConfigInfo, "LogFileThresholdLength", STRATEGY_DEFAULT, TYPE_INT32, TmpTypeDescriptor); - GetFileDirectory(TmpStr); - strcat(TmpStr, PATH_SLASH_STR); + GetFileDirectory(TmpStr); + strcat(TmpStr, PATH_SLASH_STR); TmpTypeDescriptor.str = TmpStr; ConfigAddOption(&ConfigInfo, "LogFileFolder", STRATEGY_REPLACE, TYPE_PATH, TmpTypeDescriptor); @@ -108,17 +108,17 @@ static int EnvironmentInit(void) TmpTypeDescriptor.boolean = FALSE; ConfigAddOption(&ConfigInfo, "DomainStatistic", STRATEGY_DEFAULT, TYPE_BOOLEAN, TmpTypeDescriptor); - GetFileDirectory(TmpStr); - strcat(TmpStr, PATH_SLASH_STR); - strcat(TmpStr, "StatisticTemplate.html"); + GetFileDirectory(TmpStr); + strcat(TmpStr, PATH_SLASH_STR); + strcat(TmpStr, "StatisticTemplate.html"); TmpTypeDescriptor.str = TmpStr; ConfigAddOption(&ConfigInfo, "DomainStatisticTempletFile", STRATEGY_REPLACE, TYPE_PATH, TmpTypeDescriptor); - TmpTypeDescriptor.str = ""; - ConfigAddOption(&ConfigInfo, "StatisticInsertionPosition", STRATEGY_DEFAULT, TYPE_STRING, TmpTypeDescriptor); + TmpTypeDescriptor.str = ""; + ConfigAddOption(&ConfigInfo, "StatisticInsertionPosition", STRATEGY_DEFAULT, TYPE_STRING, TmpTypeDescriptor); - TmpTypeDescriptor.INT32 = 60; - ConfigAddOption(&ConfigInfo, "StatisticUpdateInterval", STRATEGY_DEFAULT, TYPE_INT32, TmpTypeDescriptor); + TmpTypeDescriptor.INT32 = 60; + ConfigAddOption(&ConfigInfo, "StatisticUpdateInterval", STRATEGY_DEFAULT, TYPE_INT32, TmpTypeDescriptor); TmpTypeDescriptor.str = NULL; ConfigAddOption(&ConfigInfo, "Hosts", STRATEGY_APPEND, TYPE_PATH, TmpTypeDescriptor); @@ -135,9 +135,9 @@ static int EnvironmentInit(void) TmpTypeDescriptor.INT32 = 30; ConfigAddOption(&ConfigInfo, "HostsRetryInterval", STRATEGY_DEFAULT, TYPE_INT32, TmpTypeDescriptor); - GetFileDirectory(TmpStr); - strcat(TmpStr, PATH_SLASH_STR); - strcat(TmpStr, "hosts.txt"); + GetFileDirectory(TmpStr); + strcat(TmpStr, PATH_SLASH_STR); + strcat(TmpStr, "hosts.txt"); TmpTypeDescriptor.str = TmpStr; ConfigAddOption(&ConfigInfo, "HostsDownloadPath", STRATEGY_REPLACE, TYPE_PATH, TmpTypeDescriptor); @@ -162,9 +162,9 @@ static int EnvironmentInit(void) TmpTypeDescriptor.boolean = TRUE; ConfigAddOption(&ConfigInfo, "MemoryCache", STRATEGY_DEFAULT, TYPE_BOOLEAN, TmpTypeDescriptor); - GetFileDirectory(TmpStr); - strcat(TmpStr, PATH_SLASH_STR); - strcat(TmpStr, "cache"); + GetFileDirectory(TmpStr); + strcat(TmpStr, PATH_SLASH_STR); + strcat(TmpStr, "cache"); TmpTypeDescriptor.str = TmpStr; ConfigAddOption(&ConfigInfo, "CacheFile", STRATEGY_REPLACE, TYPE_PATH, TmpTypeDescriptor); @@ -180,11 +180,11 @@ static int EnvironmentInit(void) TmpTypeDescriptor.str = NULL; ConfigAddOption(&ConfigInfo, "CacheControl", STRATEGY_APPEND, TYPE_STRING, TmpTypeDescriptor); - TmpTypeDescriptor.boolean = FALSE; + TmpTypeDescriptor.boolean = FALSE; ConfigAddOption(&ConfigInfo, "ReloadCache", STRATEGY_DEFAULT, TYPE_BOOLEAN, TmpTypeDescriptor); - TmpTypeDescriptor.boolean = FALSE; - ConfigAddOption(&ConfigInfo, "OverwriteCache", STRATEGY_DEFAULT, TYPE_BOOLEAN, TmpTypeDescriptor); + TmpTypeDescriptor.boolean = FALSE; + ConfigAddOption(&ConfigInfo, "OverwriteCache", STRATEGY_DEFAULT, TYPE_BOOLEAN, TmpTypeDescriptor); TmpTypeDescriptor.str = NULL; ConfigAddOption(&ConfigInfo, "DisabledType", STRATEGY_APPEND, TYPE_STRING, TmpTypeDescriptor); @@ -201,7 +201,7 @@ static int EnvironmentInit(void) TmpTypeDescriptor.str = NULL; ConfigAddOption(&ConfigInfo, "GoodIPListAddIP", STRATEGY_APPEND, TYPE_STRING, TmpTypeDescriptor); - if( ConfigOpenFile(&ConfigInfo, ConfigFile) != 0 ) + if( ConfigOpenFile(&ConfigInfo, ConfigFile) != 0 ) { printf("WARNING: Cannot load configuration file : %s. Default options will be used. Or use `-f' to specify other configure file.\n", ConfigFile); return 0; @@ -210,22 +210,22 @@ static int EnvironmentInit(void) ConfigRead(&ConfigInfo); ConfigCloseFile(&ConfigInfo); - return 0; + return 0; } static int DaemonInit(void) { #ifdef WIN32 - char *CmdLine = GetCommandLine(); - char *NewArguments; + char *CmdLine = GetCommandLine(); + char *NewArguments; - BOOL StartUpStatus; - STARTUPINFO StartUpInfo; - PROCESS_INFORMATION ProcessInfo; + BOOL StartUpStatus; + STARTUPINFO StartUpInfo; + PROCESS_INFORMATION ProcessInfo; - CmdLine = GoToNextNonSpace(CmdLine); + CmdLine = GoToNextNonSpace(CmdLine); - if( CmdLine[0] != '\"' && CmdLine[1] != ':' ) + if( CmdLine[0] != '\"' && CmdLine[1] != ':' ) { /* CmdLine doesn't contain module name portion */ @@ -255,16 +255,16 @@ static int DaemonInit(void) strcpy(NewArguments, CmdLine); } - StartUpInfo.cb = sizeof(StartUpInfo); - StartUpInfo.lpReserved = NULL; - StartUpInfo.lpDesktop = NULL; - StartUpInfo.lpTitle = NULL; - StartUpInfo.dwFlags = STARTF_USESHOWWINDOW; - StartUpInfo.wShowWindow = SW_HIDE; - StartUpInfo.cbReserved2 = 0; - StartUpInfo.lpReserved2 = NULL; + StartUpInfo.cb = sizeof(StartUpInfo); + StartUpInfo.lpReserved = NULL; + StartUpInfo.lpDesktop = NULL; + StartUpInfo.lpTitle = NULL; + StartUpInfo.dwFlags = STARTF_USESHOWWINDOW; + StartUpInfo.wShowWindow = SW_HIDE; + StartUpInfo.cbReserved2 = 0; + StartUpInfo.lpReserved2 = NULL; - StartUpStatus = CreateProcess(NULL, + StartUpStatus = CreateProcess(NULL, NewArguments, NULL, NULL, @@ -276,18 +276,18 @@ static int DaemonInit(void) &ProcessInfo ); - SafeFree(NewArguments); + SafeFree(NewArguments); - if( StartUpStatus != FALSE ) - { - printf("deamon process pid : %lu\n", ProcessInfo.dwProcessId); - exit(0); - } else { - return 1; - } + if( StartUpStatus != FALSE ) + { + printf("deamon process pid : %lu\n", ProcessInfo.dwProcessId); + exit(0); + } else { + return 1; + } #else /* WIN32 */ - pid_t pid; + pid_t pid; if( (pid = fork()) < 0 ) { return 1; @@ -312,66 +312,66 @@ static int DaemonInit(void) static int GetDefaultConfigureFile(char *out, int OutLength) { #ifdef WIN32 - GetModulePath(out, OutLength); - strcat(out, "\\dnsforwarder.config"); + GetModulePath(out, OutLength); + strcat(out, "\\dnsforwarder.config"); #else /* WIN32 */ - GetConfigDirectory(out); - strcat(out, "/config"); + GetConfigDirectory(out); + strcat(out, "/config"); #endif /* WIN32 */ - return 0; + return 0; } #ifndef WIN32 static void PrepareEnvironment(void) { - char ConfigDirectory[2048]; + char ConfigDirectory[2048]; - GetConfigDirectory(ConfigDirectory); + GetConfigDirectory(ConfigDirectory); - if( mkdir(ConfigDirectory, S_IRWXU | S_IRGRP | S_IROTH) != 0 ) - { - int ErrorNum = GET_LAST_ERROR(); - char ErrorMessage[320]; - ErrorMessage[0] = '\0'; + if( mkdir(ConfigDirectory, S_IRWXU | S_IRGRP | S_IROTH) != 0 ) + { + int ErrorNum = GET_LAST_ERROR(); + char ErrorMessage[320]; + ErrorMessage[0] = '\0'; - GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); + GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage)); - printf("mkdir : %s failed : %s\n", ConfigDirectory, ErrorMessage); - } + printf("mkdir : %s failed : %s\n", ConfigDirectory, ErrorMessage); + } - printf("Please put configure file into `%s' and rename it to `config'.\n", ConfigDirectory); + printf("Please put configure file into `%s' and rename it to `config'.\n", ConfigDirectory); } #endif /* WIN32 */ static int ArgParse(int argc, char *argv_ori[]) { - char **argv = argv_ori; - ++argv; + char **argv = argv_ori; + ++argv; while(*argv != NULL) { - if(strcmp("-h", *argv) == 0) - { - printf("DNSforwarder by several people. Version "VERSION__" . License : GPL v3.\n Time of compilation : %s %s.\n\n", __DATE__, __TIME__); - printf("https://github.com/holmium/dnsforwarder\n\n"); - printf("Usage : %s [args].\n", strrchr(argv_ori[0], PATH_SLASH_CH) == NULL ? argv_ori[0] : strrchr(argv_ori[0], PATH_SLASH_CH) + 1); - printf(" [args] is case sensitivity and can be zero or more (in any order) of:\n" - " -f Use configuration instead of the default one.\n" - " -q Quiet mode. Do not print any information.\n" - " -D Show debug messages.\n" - " -d Daemon mode. Running at background.\n" + if(strcmp("-h", *argv) == 0) + { + printf("DNSforwarder by several people. Version "VERSION__" . License : GPL v3.\n Time of compilation : %s %s.\n\n", __DATE__, __TIME__); + printf("https://github.com/holmium/dnsforwarder\n\n"); + printf("Usage : %s [args].\n", strrchr(argv_ori[0], PATH_SLASH_CH) == NULL ? argv_ori[0] : strrchr(argv_ori[0], PATH_SLASH_CH) + 1); + printf(" [args] is case sensitivity and can be zero or more (in any order) of:\n" + " -f Use configuration instead of the default one.\n" + " -q Quiet mode. Do not print any information.\n" + " -D Show debug messages.\n" + " -d Daemon mode. Running at background.\n" #ifndef WIN32 - "\n" - " -p Prepare needed environment.\n" + "\n" + " -p Prepare needed environment.\n" #endif /* WIN32 */ - "\n" - " -h Show this help.\n" - "\n" - "Output format:\n" - " Date & Time [Udp|Tcp|Cache|Hosts|Refused|Blocked][Client IP][Queried type][Queried domain] : Message size\n" - " Results\n" - ); - exit(0); - } + "\n" + " -h Show this help.\n" + "\n" + "Output format:\n" + " Date & Time [Udp|Tcp|Cache|Hosts|Refused|Blocked][Client IP][Queried type][Queried domain] : Message size\n" + " Results\n" + ); + exit(0); + } if(strcmp("-q", *argv) == 0) { ShowMessages = FALSE; @@ -381,14 +381,14 @@ static int ArgParse(int argc, char *argv_ori[]) if(strcmp("-D", *argv) == 0) { - DebugOn = TRUE; + DebugOn = TRUE; ++argv; continue; } if(strcmp("-d", *argv) == 0) { - DeamonMode = TRUE; + DeamonMode = TRUE; ++argv; continue; } @@ -401,17 +401,17 @@ static int ArgParse(int argc, char *argv_ori[]) } #ifndef WIN32 - if( strcmp("-p", *argv) == 0 ) - { - PrepareEnvironment(); - exit(0); + if( strcmp("-p", *argv) == 0 ) + { + PrepareEnvironment(); + exit(0); - ++argv; + ++argv; continue; - } + } #endif /* WIN32 */ - printf("Unrecognisable arg `%s'. Try `-h'.\n", *argv); + printf("Unrecognisable arg `%s'. Try `-h'.\n", *argv); ++argv; } @@ -448,27 +448,27 @@ int main(int argc, char *argv[]) } #else #ifdef DOWNLOAD_LIBCURL - curl_global_init(CURL_GLOBAL_ALL); + curl_global_init(CURL_GLOBAL_ALL); #endif /* DOWNLOAD_LIBCURL */ #endif /* WIN32 */ #endif /* NODOWNLOAD */ #ifdef WIN32 - SetConsoleTitle("dnsforwarder"); + SetConsoleTitle("dnsforwarder"); #endif /* WIN32 */ - ArgParse(argc, argv); + ArgParse(argc, argv); - if( ConfigFile == NULL ) - { - ConfigFile = malloc(320); - if( ConfigFile == NULL ) - { - return -264; - } + if( ConfigFile == NULL ) + { + ConfigFile = malloc(320); + if( ConfigFile == NULL ) + { + return -264; + } - GetDefaultConfigureFile(ConfigFile, 320); - } + GetDefaultConfigureFile(ConfigFile, 320); + } printf("DNSforwarder mainly by holmium. Version "VERSION__" . License : GPL v3.\nTime of compilation : %s %s.\n\n", __DATE__, __TIME__); @@ -483,29 +483,29 @@ int main(int argc, char *argv[]) DeamonMode = FALSE; } - if( DeamonMode ) - { - if( DaemonInit() == 0 ) - { - DeamonInited = TRUE; - } else { - printf("Daemon init failed, continuing on non-daemon mode. Restart recommended.\n"); - } - } - - if( EnvironmentInit() != 0 ) + if( DeamonMode ) + { + if( DaemonInit() == 0 ) + { + DeamonInited = TRUE; + } else { + printf("Daemon init failed, continuing on non-daemon mode. Restart recommended.\n"); + } + } + + if( EnvironmentInit() != 0 ) { return -498; } putchar('\n'); - if( DeamonInited ) + if( DeamonInited ) { ShowMessages = FALSE; } - if( Log_Init(&ConfigInfo, ShowMessages, DebugOn) != 0 ) + if( Log_Init(&ConfigInfo, ShowMessages, DebugOn) != 0 ) { return -291; } @@ -517,7 +517,7 @@ int main(int argc, char *argv[]) INFO("Running on daemon mode.\n"); } - if( TimedTask_Init() != 0 ) + if( TimedTask_Init() != 0 ) { return -505; } @@ -549,7 +549,7 @@ int main(int argc, char *argv[]) #endif /* WIN32 */ #endif /* NODOWNLOAD */ - ExitThisThread(); + ExitThisThread(); return 0; } diff --git a/mcontext.c b/mcontext.c index ecd04c67..c3123b37 100755 --- a/mcontext.c +++ b/mcontext.c @@ -14,7 +14,7 @@ static int ModuleContext_Swep_Collect(Bst *t, Array *Pending ) { - time_t Now = time(NULL); + time_t Now = time(NULL); if( Now - Context->t > 2 ) { @@ -127,12 +127,12 @@ static int ModuleContextCompare(const void *_1, const void *_2) const ModuleContextItem *One = (ModuleContextItem *)_1; const ModuleContextItem *Two = (ModuleContextItem *)_2; - if( One->i != Two->i ) - { - return (int)(One->i) - (int)(Two->i); - } else { - return One->h.HashValue - Two->h.HashValue; - } + if( One->i != Two->i ) + { + return (int)(One->i) - (int)(Two->i); + } else { + return One->h.HashValue - Two->h.HashValue; + } } int ModuleContext_Init(ModuleContext *c) diff --git a/mcontext.h b/mcontext.h index f1c7d1b4..4d4f3626 100755 --- a/mcontext.h +++ b/mcontext.h @@ -11,7 +11,7 @@ typedef struct _ModuleContext ModuleContext; struct _ModuleContext{ /* private */ - Bst d; + Bst d; /* public */ int (*Add)(ModuleContext *c, diff --git a/mmgr.c b/mmgr.c index 65049cad..12de21fe 100755 --- a/mmgr.c +++ b/mmgr.c @@ -37,7 +37,7 @@ static StableBuffer *Modules = NULL; /* Storing ModuleInterfaces */ static Array *ModuleArray = NULL; /* ModuleInterfaces' references */ static StringChunk *Distributor = NULL; /* Domain-to-ModuleInterface mapping */ -static RWLock ModulesLock; +static RWLock ModulesLock; static ConfigFileInfo *CurrConfigInfo = NULL; static int MappingAModule(ModuleMap *ModuleMap, diff --git a/querydnslistentcp.c b/querydnslistentcp.c index 979623ff..c8f36f64 100755 --- a/querydnslistentcp.c +++ b/querydnslistentcp.c @@ -13,389 +13,389 @@ #include "addresslist.h" /* Variables */ -static BOOL Inited = FALSE; +static BOOL Inited = FALSE; -static SOCKET TCPIncomeSocket; +static SOCKET TCPIncomeSocket; -static SOCKET TCPOutcomeSocket; -static Address_Type TCPOutcomeAddress; +static SOCKET TCPOutcomeSocket; +static Address_Type TCPOutcomeAddress; -static int RefusingResponseCode = 0; +static int RefusingResponseCode = 0; -static QueryContext Context; +static QueryContext Context; /* Functions */ int QueryDNSListenTCPInit(ConfigFileInfo *ConfigInfo) { - RefusingResponseCode = ConfigGetInt32(ConfigInfo, "RefusingResponseCode"); + RefusingResponseCode = ConfigGetInt32(ConfigInfo, "RefusingResponseCode"); - TCPIncomeSocket = InternalInterface_OpenTCP(MAIN_WORKING_ADDRESS, INTERNAL_INTERFACE_TCP_INCOME, MAIN_WORKING_PORT); - if( TCPIncomeSocket == INVALID_SOCKET ) - { - ShowFatalMessage("Opening TCP socket failed.", GET_LAST_ERROR()); - return -1; - } else { - INFO("TCP socket %s:%d created.\n", MAIN_WORKING_ADDRESS, MAIN_WORKING_PORT); - } + TCPIncomeSocket = InternalInterface_OpenTCP(MAIN_WORKING_ADDRESS, INTERNAL_INTERFACE_TCP_INCOME, MAIN_WORKING_PORT); + if( TCPIncomeSocket == INVALID_SOCKET ) + { + ShowFatalMessage("Opening TCP socket failed.", GET_LAST_ERROR()); + return -1; + } else { + INFO("TCP socket %s:%d created.\n", MAIN_WORKING_ADDRESS, MAIN_WORKING_PORT); + } - InternalInterface_GetAddress(INTERNAL_INTERFACE_TCP_INCOME, NULL); + InternalInterface_GetAddress(INTERNAL_INTERFACE_TCP_INCOME, NULL); - TCPOutcomeSocket = InternalInterface_TryBindLocal(10000, &TCPOutcomeAddress); + TCPOutcomeSocket = InternalInterface_TryBindLocal(10000, &TCPOutcomeAddress); - InternalInterface_InitQueryContext(&Context); + InternalInterface_InitQueryContext(&Context); - Inited = TRUE; + Inited = TRUE; - return 0; + return 0; } static int Query(char *Content, int ContentLength, int BufferLength, SOCKET ThisSocket) { - int State; - char *RequestEntity = Content + sizeof(ControlHeader); - ControlHeader *Header = (ControlHeader *)Content; - int RequestLength = ContentLength - sizeof(ControlHeader); - uint16_t TCPLength = htons(RequestLength); - - Header->RequestingDomain[0] = '\0'; - - if( DNSGetHostName(RequestEntity, - RequestLength, - DNSJumpHeader(RequestEntity), - Header->RequestingDomain, - sizeof(Header->RequestingDomain) - ) - < 0 ) - { - return -1; - } - - StrToLower(Header->RequestingDomain); - - Header->RequestingType = - (DNSRecordType)DNSGetRecordType(DNSJumpHeader(RequestEntity)); - - Header->RequestingDomainHashValue = HASH(Header->RequestingDomain, 0); - - State = QueryBase(Content, ContentLength, BufferLength, TCPOutcomeSocket); - - switch( State ) - { - case QUERY_RESULT_SUCCESS: - InternalInterface_QueryContextAddTCP(&Context, Header, ThisSocket); - return 0; - break; - - case QUERY_RESULT_DISABLE: - ((DNSHeader *)(RequestEntity))->Flags.Direction = 1; - ((DNSHeader *)(RequestEntity))->Flags.RecursionAvailable = 1; - ((DNSHeader *)(RequestEntity))->Flags.ResponseCode = RefusingResponseCode; - send(ThisSocket, (const char *)&TCPLength, 2, 0); - send(ThisSocket, RequestEntity, RequestLength, 0); - return -1; - break; - - case QUERY_RESULT_ERROR: - return -1; - break; - - default: /* Cache */ - { - uint16_t NewTCPLength = htons(State); - - send(ThisSocket, (const char *)&NewTCPLength, 2, 0); - send(ThisSocket, RequestEntity, State, 0); - return 0; - } - break; - } + int State; + char *RequestEntity = Content + sizeof(ControlHeader); + ControlHeader *Header = (ControlHeader *)Content; + int RequestLength = ContentLength - sizeof(ControlHeader); + uint16_t TCPLength = htons(RequestLength); + + Header->RequestingDomain[0] = '\0'; + + if( DNSGetHostName(RequestEntity, + RequestLength, + DNSJumpHeader(RequestEntity), + Header->RequestingDomain, + sizeof(Header->RequestingDomain) + ) + < 0 ) + { + return -1; + } + + StrToLower(Header->RequestingDomain); + + Header->RequestingType = + (DNSRecordType)DNSGetRecordType(DNSJumpHeader(RequestEntity)); + + Header->RequestingDomainHashValue = HASH(Header->RequestingDomain, 0); + + State = QueryBase(Content, ContentLength, BufferLength, TCPOutcomeSocket); + + switch( State ) + { + case QUERY_RESULT_SUCCESS: + InternalInterface_QueryContextAddTCP(&Context, Header, ThisSocket); + return 0; + break; + + case QUERY_RESULT_DISABLE: + ((DNSHeader *)(RequestEntity))->Flags.Direction = 1; + ((DNSHeader *)(RequestEntity))->Flags.RecursionAvailable = 1; + ((DNSHeader *)(RequestEntity))->Flags.ResponseCode = RefusingResponseCode; + send(ThisSocket, (const char *)&TCPLength, 2, 0); + send(ThisSocket, RequestEntity, RequestLength, 0); + return -1; + break; + + case QUERY_RESULT_ERROR: + return -1; + break; + + default: /* Cache */ + { + uint16_t NewTCPLength = htons(State); + + send(ThisSocket, (const char *)&NewTCPLength, 2, 0); + send(ThisSocket, RequestEntity, State, 0); + return 0; + } + break; + } } typedef struct _SocketInfo { - SOCKET Socket; - char Address[LENGTH_OF_IPV6_ADDRESS_ASCII + 1]; - time_t TimeAdd; + SOCKET Socket; + char Address[LENGTH_OF_IPV6_ADDRESS_ASCII + 1]; + time_t TimeAdd; } SocketInfo; -static Bst si; +static Bst si; static int SocketInfoCompare(const SocketInfo *_1, const SocketInfo *_2) { - return (int)(_1->Socket) - (int)(_2->Socket); + return (int)(_1->Socket) - (int)(_2->Socket); } static int InitSocketInfo(void) { - return Bst_Init(&si, NULL, sizeof(SocketInfo), (int (*)(const void *, const void *))SocketInfoCompare); + return Bst_Init(&si, NULL, sizeof(SocketInfo), (int (*)(const void *, const void *))SocketInfoCompare); } static SOCKET SocketInfoMatch(fd_set *ReadySet, fd_set *ReadSet, char *ClientAddress, int32_t *Number) { - int32_t Start = -1; - SocketInfo *Info; - - time_t Now = time(NULL); - - Info = Bst_Enum(&si, &Start); - while( Info != NULL ) - { - if( FD_ISSET(Info->Socket, ReadySet) ) - { - Info->TimeAdd = Now; - strcpy(ClientAddress, Info->Address); - if( Number != NULL ) - { - *Number = Start; - } - return Info->Socket; - } - - if( Now - Info->TimeAdd > 2 ) - { - CLOSE_SOCKET(Info->Socket); - FD_CLR(Info->Socket, ReadSet); - Bst_Delete_ByNumber(&si, Start); - } - - Info = Bst_Enum(&si, &Start); - } - - return INVALID_SOCKET; + int32_t Start = -1; + SocketInfo *Info; + + time_t Now = time(NULL); + + Info = Bst_Enum(&si, &Start); + while( Info != NULL ) + { + if( FD_ISSET(Info->Socket, ReadySet) ) + { + Info->TimeAdd = Now; + strcpy(ClientAddress, Info->Address); + if( Number != NULL ) + { + *Number = Start; + } + return Info->Socket; + } + + if( Now - Info->TimeAdd > 2 ) + { + CLOSE_SOCKET(Info->Socket); + FD_CLR(Info->Socket, ReadSet); + Bst_Delete_ByNumber(&si, Start); + } + + Info = Bst_Enum(&si, &Start); + } + + return INVALID_SOCKET; } static int SocketInfoAdd(SOCKET Socket, const char *Address) { - SocketInfo New; + SocketInfo New; - New.Socket = Socket; - strcpy(New.Address, Address); - New.TimeAdd = time(NULL); + New.Socket = Socket; + strcpy(New.Address, Address); + New.TimeAdd = time(NULL); - return Bst_Add(&si, &New); + return Bst_Add(&si, &New); } static BOOL SocketInfoSwep(fd_set *ReadSet) { - int32_t Start = -1; - SocketInfo *Info; + int32_t Start = -1; + SocketInfo *Info; - time_t Now = time(NULL); + time_t Now = time(NULL); - Info = Bst_Enum(&si, &Start); - while( Info != NULL ) - { - if( Now - Info->TimeAdd > 2 ) - { - CLOSE_SOCKET(Info->Socket); - FD_CLR(Info->Socket, ReadSet); + Info = Bst_Enum(&si, &Start); + while( Info != NULL ) + { + if( Now - Info->TimeAdd > 2 ) + { + CLOSE_SOCKET(Info->Socket); + FD_CLR(Info->Socket, ReadSet); - INFO("TCP connection to client %s closed.\n", Info->Address); + INFO("TCP connection to client %s closed.\n", Info->Address); - Bst_Delete_ByNumber(&si, Start); - } + Bst_Delete_ByNumber(&si, Start); + } - Info = Bst_Enum(&si, &Start); - } + Info = Bst_Enum(&si, &Start); + } - return Bst_IsEmpty(&si); + return Bst_IsEmpty(&si); } static void SendBack(char *Result, int Length) { - ControlHeader *Header = (ControlHeader *)Result; - char *RequestEntity = Result + sizeof(ControlHeader); - uint16_t Identifier = *(uint16_t *)RequestEntity; - int32_t Number; - QueryContextEntry *Entry; - uint16_t EntityLength = Length - sizeof(ControlHeader); - uint16_t EntityLength_n = htons(EntityLength); + ControlHeader *Header = (ControlHeader *)Result; + char *RequestEntity = Result + sizeof(ControlHeader); + uint16_t Identifier = *(uint16_t *)RequestEntity; + int32_t Number; + QueryContextEntry *Entry; + uint16_t EntityLength = Length - sizeof(ControlHeader); + uint16_t EntityLength_n = htons(EntityLength); - Number = InternalInterface_QueryContextFind(&Context, Identifier, Header->RequestingDomainHashValue); - if( Number < 0 ) - { - return; - } + Number = InternalInterface_QueryContextFind(&Context, Identifier, Header->RequestingDomainHashValue); + if( Number < 0 ) + { + return; + } - Entry = Bst_GetDataByNumber(&Context, Number); + Entry = Bst_GetDataByNumber(&Context, Number); - send(Entry->Context.Socket, (const char *)&EntityLength_n, 2, 0); - send(Entry->Context.Socket, RequestEntity, EntityLength, 0); + send(Entry->Context.Socket, (const char *)&EntityLength_n, 2, 0); + send(Entry->Context.Socket, RequestEntity, EntityLength, 0); - InternalInterface_QueryContextRemoveByNumber(&Context, Number); + InternalInterface_QueryContextRemoveByNumber(&Context, Number); } static int QueryDNSListenTCP(void) { - int MaxFd = TCPIncomeSocket > TCPOutcomeSocket ? TCPIncomeSocket : TCPOutcomeSocket; - - static fd_set ReadSet, ReadySet; - - int NumberOfQueryBeforeSwep = 0; - - static const struct timeval LongTime = {3600, 0}; - static const struct timeval ShortTime = {10, 0}; - - struct timeval TimeLimit = LongTime; - - static char RequestEntity[2048]; - ControlHeader *Header = (ControlHeader *)RequestEntity; - - InternalInterface_InitControlHeader(Header); - - memcpy(&(Header->BackAddress), &TCPOutcomeAddress, sizeof(Address_Type)); - Header->NeededHeader = TRUE; - - InitSocketInfo(); - - FD_ZERO(&ReadSet); - FD_ZERO(&ReadySet); - - FD_SET(TCPIncomeSocket, &ReadSet); - FD_SET(TCPOutcomeSocket, &ReadSet); - - while( TRUE ) - { - ReadySet = ReadSet; - - switch( select(MaxFd + 1, &ReadySet, NULL, NULL, &TimeLimit) ) - { - case SOCKET_ERROR: - { - int LastError = GET_LAST_ERROR(); - ERRORMSG("SOCKET_ERROR Reached, 1.\n"); - if( FatalErrorDecideding(LastError) != 0 ) - { - ERRORMSG("\n\n\n\n\n\n\n\n\n\n"); - ERRORMSG(" !!!!! Something bad happend, please restart this program. %d\n", LastError); - while( TRUE ) SLEEP(100000); - } - } - break; - - case 0: - if( SocketInfoSwep(&ReadSet) == TRUE ) - { - Bst_Reset(&Context); - TimeLimit = LongTime; - } else { - InternalInterface_QueryContextSwep(&Context, 10, NULL); - TimeLimit = ShortTime; - } - - NumberOfQueryBeforeSwep = 0; - break; - - default: - TimeLimit = ShortTime; - - ++NumberOfQueryBeforeSwep; - if( NumberOfQueryBeforeSwep > 1024 ) - { - InternalInterface_QueryContextSwep(&Context, 2, NULL); - SocketInfoSwep(&ReadSet); - NumberOfQueryBeforeSwep = 0; - } - - if( FD_ISSET(TCPIncomeSocket, &ReadySet) ) - { - SOCKET NewSocket; - Address_Type Address; - socklen_t AddrLen; - - char AddressString[LENGTH_OF_IPV6_ADDRESS_ASCII + 1]; - - if( MAIN_FAMILY == AF_INET ) - { - AddrLen = sizeof(struct sockaddr); - NewSocket = accept(TCPIncomeSocket, - (struct sockaddr *)&(Address.Addr.Addr4), - (socklen_t *)&AddrLen - ); - } else { - AddrLen = sizeof(struct sockaddr_in6); - NewSocket = accept(TCPIncomeSocket, - (struct sockaddr *)&(Address.Addr.Addr6), - (socklen_t *)&AddrLen - ); - } - - if( NewSocket != INVALID_SOCKET ) - { - FD_SET(NewSocket, &ReadSet); - - if( MAIN_FAMILY == AF_INET ) - { - strcpy(AddressString, inet_ntoa(Address.Addr.Addr4.sin_addr)); - } else { - IPv6AddressToAsc(&(Address.Addr.Addr6.sin6_addr), AddressString); - } - - if( NewSocket > MaxFd ) - { - MaxFd = NewSocket; - } - - SocketInfoAdd(NewSocket, AddressString); - INFO("TCP connection to client %s established.\n", AddressString); - } - - } else if( FD_ISSET(TCPOutcomeSocket, &ReadySet) ) - { - static char Result[2048]; - int State; - - State = recvfrom(TCPOutcomeSocket, Result, sizeof(Result), 0, NULL, NULL); - if( State > 0 ) - { - SendBack(Result, State); - } - } else { - SOCKET Socket; - int State; - - int32_t Number; - - Socket = SocketInfoMatch(&ReadySet, &ReadSet, Header->Agent, &Number); - - if( Socket != INVALID_SOCKET ) - { - uint16_t TCPLength; - - if( recv(Socket, (char *)&TCPLength, 2, MSG_NOSIGNAL) < 2 ) - { - Bst_Delete_ByNumber(&si, Number); - FD_CLR(Socket, &ReadSet); - CLOSE_SOCKET(Socket); - break; - } - - TCPLength = ntohs(TCPLength); - - State = recv(Socket, RequestEntity + sizeof(ControlHeader), sizeof(RequestEntity) - sizeof(ControlHeader), MSG_NOSIGNAL); - if( State < 1 ) - { - Bst_Delete_ByNumber(&si, Number); - FD_CLR(Socket, &ReadSet); - CLOSE_SOCKET(Socket); - INFO("Lost TCP connection to client %s.\n", Header->Agent); - break; - } - - Query(RequestEntity, State + sizeof(ControlHeader), sizeof(RequestEntity), Socket); - } - } - break; - } - } - - return 0; + int MaxFd = TCPIncomeSocket > TCPOutcomeSocket ? TCPIncomeSocket : TCPOutcomeSocket; + + static fd_set ReadSet, ReadySet; + + int NumberOfQueryBeforeSwep = 0; + + static const struct timeval LongTime = {3600, 0}; + static const struct timeval ShortTime = {10, 0}; + + struct timeval TimeLimit = LongTime; + + static char RequestEntity[2048]; + ControlHeader *Header = (ControlHeader *)RequestEntity; + + InternalInterface_InitControlHeader(Header); + + memcpy(&(Header->BackAddress), &TCPOutcomeAddress, sizeof(Address_Type)); + Header->NeededHeader = TRUE; + + InitSocketInfo(); + + FD_ZERO(&ReadSet); + FD_ZERO(&ReadySet); + + FD_SET(TCPIncomeSocket, &ReadSet); + FD_SET(TCPOutcomeSocket, &ReadSet); + + while( TRUE ) + { + ReadySet = ReadSet; + + switch( select(MaxFd + 1, &ReadySet, NULL, NULL, &TimeLimit) ) + { + case SOCKET_ERROR: + { + int LastError = GET_LAST_ERROR(); + ERRORMSG("SOCKET_ERROR Reached, 1.\n"); + if( FatalErrorDecideding(LastError) != 0 ) + { + ERRORMSG("\n\n\n\n\n\n\n\n\n\n"); + ERRORMSG(" !!!!! Something bad happend, please restart this program. %d\n", LastError); + while( TRUE ) SLEEP(100000); + } + } + break; + + case 0: + if( SocketInfoSwep(&ReadSet) == TRUE ) + { + Bst_Reset(&Context); + TimeLimit = LongTime; + } else { + InternalInterface_QueryContextSwep(&Context, 10, NULL); + TimeLimit = ShortTime; + } + + NumberOfQueryBeforeSwep = 0; + break; + + default: + TimeLimit = ShortTime; + + ++NumberOfQueryBeforeSwep; + if( NumberOfQueryBeforeSwep > 1024 ) + { + InternalInterface_QueryContextSwep(&Context, 2, NULL); + SocketInfoSwep(&ReadSet); + NumberOfQueryBeforeSwep = 0; + } + + if( FD_ISSET(TCPIncomeSocket, &ReadySet) ) + { + SOCKET NewSocket; + Address_Type Address; + socklen_t AddrLen; + + char AddressString[LENGTH_OF_IPV6_ADDRESS_ASCII + 1]; + + if( MAIN_FAMILY == AF_INET ) + { + AddrLen = sizeof(struct sockaddr); + NewSocket = accept(TCPIncomeSocket, + (struct sockaddr *)&(Address.Addr.Addr4), + (socklen_t *)&AddrLen + ); + } else { + AddrLen = sizeof(struct sockaddr_in6); + NewSocket = accept(TCPIncomeSocket, + (struct sockaddr *)&(Address.Addr.Addr6), + (socklen_t *)&AddrLen + ); + } + + if( NewSocket != INVALID_SOCKET ) + { + FD_SET(NewSocket, &ReadSet); + + if( MAIN_FAMILY == AF_INET ) + { + strcpy(AddressString, inet_ntoa(Address.Addr.Addr4.sin_addr)); + } else { + IPv6AddressToAsc(&(Address.Addr.Addr6.sin6_addr), AddressString); + } + + if( NewSocket > MaxFd ) + { + MaxFd = NewSocket; + } + + SocketInfoAdd(NewSocket, AddressString); + INFO("TCP connection to client %s established.\n", AddressString); + } + + } else if( FD_ISSET(TCPOutcomeSocket, &ReadySet) ) + { + static char Result[2048]; + int State; + + State = recvfrom(TCPOutcomeSocket, Result, sizeof(Result), 0, NULL, NULL); + if( State > 0 ) + { + SendBack(Result, State); + } + } else { + SOCKET Socket; + int State; + + int32_t Number; + + Socket = SocketInfoMatch(&ReadySet, &ReadSet, Header->Agent, &Number); + + if( Socket != INVALID_SOCKET ) + { + uint16_t TCPLength; + + if( recv(Socket, (char *)&TCPLength, 2, MSG_NOSIGNAL) < 2 ) + { + Bst_Delete_ByNumber(&si, Number); + FD_CLR(Socket, &ReadSet); + CLOSE_SOCKET(Socket); + break; + } + + TCPLength = ntohs(TCPLength); + + State = recv(Socket, RequestEntity + sizeof(ControlHeader), sizeof(RequestEntity) - sizeof(ControlHeader), MSG_NOSIGNAL); + if( State < 1 ) + { + Bst_Delete_ByNumber(&si, Number); + FD_CLR(Socket, &ReadSet); + CLOSE_SOCKET(Socket); + INFO("Lost TCP connection to client %s.\n", Header->Agent); + break; + } + + Query(RequestEntity, State + sizeof(ControlHeader), sizeof(RequestEntity), Socket); + } + } + break; + } + } + + return 0; } void QueryDNSListenTCPStart(void) { - ThreadHandle t; + ThreadHandle t; - CREATE_THREAD(QueryDNSListenTCP, NULL, t); - DETACH_THREAD(t); + CREATE_THREAD(QueryDNSListenTCP, NULL, t); + DETACH_THREAD(t); } diff --git a/readconfig.c b/readconfig.c index 31c6ddd4..c7eb5832 100755 --- a/readconfig.c +++ b/readconfig.c @@ -9,9 +9,9 @@ int ConfigInitInfo(ConfigFileInfo *Info) { - Info->fp = NULL; + Info->fp = NULL; - if( StringList_Init(&(Info->StrBuffer), NULL, NULL) != 0 ) + if( StringList_Init(&(Info->StrBuffer), NULL, NULL) != 0 ) { return -14; } @@ -21,21 +21,21 @@ int ConfigInitInfo(ConfigFileInfo *Info) return -19; } - return 0; + return 0; } int ConfigOpenFile(ConfigFileInfo *Info, const char *File) { - Info->fp = fopen(File, "r"); - if( Info->fp == NULL ) - return -56; - else - return 0; + Info->fp = fopen(File, "r"); + if( Info->fp == NULL ) + return -56; + else + return 0; } int ConfigCloseFile(ConfigFileInfo *Info) { - return fclose(Info->fp); + return fclose(Info->fp); } int ConfigAddOption(ConfigFileInfo *Info, @@ -45,42 +45,42 @@ int ConfigAddOption(ConfigFileInfo *Info, VType Initial ) { - ConfigOption New; - - New.Type = Type; - New.Status = STATUS_DEFAULT_VALUE; - New.Strategy = Strategy; - - switch( Type ) - { - case TYPE_INT32: - New.Holder.INT32 = Initial.INT32; - break; - - case TYPE_BOOLEAN: - New.Holder.boolean = Initial.boolean; - break; - - case TYPE_PATH: - case TYPE_STRING: - if( StringList_Init(&(New.Holder.str), Initial.str, ",") != 0 ) - { - return 2; - } - - New.Delimiters = ","; + ConfigOption New; + + New.Type = Type; + New.Status = STATUS_DEFAULT_VALUE; + New.Strategy = Strategy; + + switch( Type ) + { + case TYPE_INT32: + New.Holder.INT32 = Initial.INT32; + break; + + case TYPE_BOOLEAN: + New.Holder.boolean = Initial.boolean; + break; + + case TYPE_PATH: + case TYPE_STRING: + if( StringList_Init(&(New.Holder.str), Initial.str, ",") != 0 ) + { + return 2; + } + + New.Delimiters = ","; if( New.Delimiters == NULL ) { return -68; } - break; + break; - default: - break; - } + default: + break; + } - return StringChunk_Add(&(Info->Options), KeyName, (const char *)&New, sizeof(ConfigOption)); + return StringChunk_Add(&(Info->Options), KeyName, (const char *)&New, sizeof(ConfigOption)); } int ConfigAddAlias(ConfigFileInfo *Info, @@ -90,27 +90,27 @@ int ConfigAddAlias(ConfigFileInfo *Info, const char *StringDelimiters ) { - ConfigOption New; + ConfigOption New; - New.Type = TYPE_ALIAS; + New.Type = TYPE_ALIAS; - New.Holder.Aliasing.Target = DUP_STRING(Info, Target); + New.Holder.Aliasing.Target = DUP_STRING(Info, Target); - if( Prepending != NULL ) + if( Prepending != NULL ) { New.Holder.Aliasing.Prepending = DUP_STRING(Info, Prepending); } else { New.Holder.Aliasing.Prepending = NULL; } - if( StringDelimiters != NULL ) + if( StringDelimiters != NULL ) { New.Delimiters = DUP_STRING(Info, StringDelimiters); } else { New.Delimiters = NULL; } - return StringChunk_Add(&(Info->Options), + return StringChunk_Add(&(Info->Options), Alias, (const char *)&New, sizeof(ConfigOption) @@ -124,13 +124,13 @@ static ConfigOption *GetOptionOfAInfo(ConfigFileInfo *Info, const char **StringDelimiters ) { - ConfigOption *Option; + ConfigOption *Option; - if( StringChunk_Match_NoWildCard(&(Info->Options), KeyName, NULL, (void **)&Option) == TRUE ) - { - if( Option->Type == TYPE_ALIAS ) - { - if( Prepending != NULL ) + if( StringChunk_Match_NoWildCard(&(Info->Options), KeyName, NULL, (void **)&Option) == TRUE ) + { + if( Option->Type == TYPE_ALIAS ) + { + if( Prepending != NULL ) { *Prepending = Option->Holder.Aliasing.Prepending; } @@ -140,17 +140,17 @@ static ConfigOption *GetOptionOfAInfo(ConfigFileInfo *Info, *StringDelimiters = Option->Delimiters; } - return GetOptionOfAInfo(Info, + return GetOptionOfAInfo(Info, Option->Holder.Aliasing.Target, Prepending, StringDelimiters ); - } else { - return Option; - } - } else { - return NULL; - } + } else { + return Option; + } + } else { + return NULL; + } } int ConfigSetStringDelimiters(ConfigFileInfo *Info, @@ -182,101 +182,101 @@ int ConfigSetStringDelimiters(ConfigFileInfo *Info, static BOOL GetBooleanValueFromString(const char *str) { - if( isdigit(*str) ) - { - if( *str == '0' ) - return FALSE; - else - return TRUE; - } else { - char Dump[8]; - - strncpy(Dump, str, sizeof(Dump)); - Dump[sizeof(Dump) - 1] = '\0'; - - StrToLower(Dump); - - if( strstr(Dump, "false") != NULL ) - return FALSE; - else if( strstr(Dump, "true") != NULL ) - return TRUE; - - if( strstr(Dump, "no") != NULL ) - return FALSE; - else if( strstr(Dump, "yes") != NULL ) - return TRUE; - } - - return FALSE; + if( isdigit(*str) ) + { + if( *str == '0' ) + return FALSE; + else + return TRUE; + } else { + char Dump[8]; + + strncpy(Dump, str, sizeof(Dump)); + Dump[sizeof(Dump) - 1] = '\0'; + + StrToLower(Dump); + + if( strstr(Dump, "false") != NULL ) + return FALSE; + else if( strstr(Dump, "true") != NULL ) + return TRUE; + + if( strstr(Dump, "no") != NULL ) + return FALSE; + else if( strstr(Dump, "yes") != NULL ) + return TRUE; + } + + return FALSE; } static void ParseBoolean(ConfigOption *Option, const char *Value) { - switch (Option->Strategy) - { - case STRATEGY_APPEND_DISCARD_DEFAULT: - if( Option->Status == STATUS_DEFAULT_VALUE ) - { - Option->Strategy = STRATEGY_APPEND; - } - /* No break */ + switch (Option->Strategy) + { + case STRATEGY_APPEND_DISCARD_DEFAULT: + if( Option->Status == STATUS_DEFAULT_VALUE ) + { + Option->Strategy = STRATEGY_APPEND; + } + /* No break */ - case STRATEGY_DEFAULT: - case STRATEGY_REPLACE: + case STRATEGY_DEFAULT: + case STRATEGY_REPLACE: - Option->Holder.boolean = GetBooleanValueFromString(Value); + Option->Holder.boolean = GetBooleanValueFromString(Value); - Option->Status = STATUS_SPECIAL_VALUE; - break; + Option->Status = STATUS_SPECIAL_VALUE; + break; - case STRATEGY_APPEND: - { - BOOL SpecifiedValue; + case STRATEGY_APPEND: + { + BOOL SpecifiedValue; - SpecifiedValue = GetBooleanValueFromString(Value); - Option->Holder.boolean |= SpecifiedValue; + SpecifiedValue = GetBooleanValueFromString(Value); + Option->Holder.boolean |= SpecifiedValue; - Option->Status = STATUS_SPECIAL_VALUE; - } - break; + Option->Status = STATUS_SPECIAL_VALUE; + } + break; - default: - break; + default: + break; - } + } } static void ParseInt32(ConfigOption *Option, const char *Value) { - switch (Option->Strategy) - { - case STRATEGY_APPEND_DISCARD_DEFAULT: - if( Option->Status == STATUS_DEFAULT_VALUE ) - { - Option->Strategy = STRATEGY_APPEND; - } - /* No break */ - - case STRATEGY_DEFAULT: - case STRATEGY_REPLACE: - sscanf(Value, "%d", &(Option->Holder.INT32)); - Option->Status = STATUS_SPECIAL_VALUE; - break; - - case STRATEGY_APPEND: - { - int32_t SpecifiedValue; - - sscanf(Value, "%d", &SpecifiedValue); - Option->Holder.INT32 += SpecifiedValue; - - Option->Status = STATUS_SPECIAL_VALUE; - } - break; - - default: - break; - } + switch (Option->Strategy) + { + case STRATEGY_APPEND_DISCARD_DEFAULT: + if( Option->Status == STATUS_DEFAULT_VALUE ) + { + Option->Strategy = STRATEGY_APPEND; + } + /* No break */ + + case STRATEGY_DEFAULT: + case STRATEGY_REPLACE: + sscanf(Value, "%d", &(Option->Holder.INT32)); + Option->Status = STATUS_SPECIAL_VALUE; + break; + + case STRATEGY_APPEND: + { + int32_t SpecifiedValue; + + sscanf(Value, "%d", &SpecifiedValue); + Option->Holder.INT32 += SpecifiedValue; + + Option->Status = STATUS_SPECIAL_VALUE; + } + break; + + default: + break; + } } static void ParseString(ConfigOption *Option, @@ -289,47 +289,47 @@ static void ParseString(ConfigOption *Option, int BufferLength ) { - switch( Option->Strategy ) - { - case STRATEGY_APPEND_DISCARD_DEFAULT: - if( Option->Status == STATUS_DEFAULT_VALUE ) - { - Option->Strategy = STRATEGY_APPEND; - } - /* No break */ - - case STRATEGY_DEFAULT: - case STRATEGY_REPLACE: - Option->Holder.str.Clear(&(Option->Holder.str)); - /* No break */ - - case STRATEGY_APPEND: - if( Option->Holder.str.Add(&(Option->Holder.str), + switch( Option->Strategy ) + { + case STRATEGY_APPEND_DISCARD_DEFAULT: + if( Option->Status == STATUS_DEFAULT_VALUE ) + { + Option->Strategy = STRATEGY_APPEND; + } + /* No break */ + + case STRATEGY_DEFAULT: + case STRATEGY_REPLACE: + Option->Holder.str.Clear(&(Option->Holder.str)); + /* No break */ + + case STRATEGY_APPEND: + if( Option->Holder.str.Add(&(Option->Holder.str), Value, Delimiters ) == NULL ) - { - return; - } - Option->Status = STATUS_SPECIAL_VALUE; - break; + { + return; + } + Option->Status = STATUS_SPECIAL_VALUE; + break; - default: - return; - break; - } + default: + return; + break; + } - while( ReadStatus != READ_DONE ){ + while( ReadStatus != READ_DONE ){ - ReadStatus = ReadLine(fp, Buffer, BufferLength); - if( ReadStatus == READ_FAILED_OR_END ) - break; + ReadStatus = ReadLine(fp, Buffer, BufferLength); + if( ReadStatus == READ_FAILED_OR_END ) + break; - Option->Holder.str.AppendLast(&(Option->Holder.str), Buffer, Delimiters); - } + Option->Holder.str.AppendLast(&(Option->Holder.str), Buffer, Delimiters); + } - if( Trim ) + if( Trim ) { Option->Holder.str.TrimAll(&(Option->Holder.str), NULL); } @@ -337,60 +337,60 @@ static void ParseString(ConfigOption *Option, static char *TrimPath(char *Path) { - char *LastCharacter = StrRNpbrk(Path, "\""); - char *FirstLetter; - - if( LastCharacter != NULL ) - { - *(LastCharacter + 1) = '\0'; - - FirstLetter = StrNpbrk(Path, "\"\t "); - if( FirstLetter != NULL ) - { - memmove(Path, FirstLetter, strlen(FirstLetter) + 1); - return Path; - } else { - return NULL; - } - } else { - return NULL; - } + char *LastCharacter = StrRNpbrk(Path, "\""); + char *FirstLetter; + + if( LastCharacter != NULL ) + { + *(LastCharacter + 1) = '\0'; + + FirstLetter = StrNpbrk(Path, "\"\t "); + if( FirstLetter != NULL ) + { + memmove(Path, FirstLetter, strlen(FirstLetter) + 1); + return Path; + } else { + return NULL; + } + } else { + return NULL; + } } int ConfigRead(ConfigFileInfo *Info) { - int NumOfRead = 0; + int NumOfRead = 0; - char Buffer[2048]; - char *ValuePos; - ReadLineStatus ReadStatus; + char Buffer[2048]; + char *ValuePos; + ReadLineStatus ReadStatus; - char *KeyName; - ConfigOption *Option; + char *KeyName; + ConfigOption *Option; - const char *Prepending; - const char *StringDelimiters; + const char *Prepending; + const char *StringDelimiters; - while(TRUE){ - ReadStatus = ReadLine(Info->fp, Buffer, sizeof(Buffer)); - if( ReadStatus == READ_FAILED_OR_END ) - return NumOfRead; + while(TRUE){ + ReadStatus = ReadLine(Info->fp, Buffer, sizeof(Buffer)); + if( ReadStatus == READ_FAILED_OR_END ) + return NumOfRead; - ValuePos = SplitNameAndValue(Buffer, " \t="); - if( ValuePos == NULL ) - continue; + ValuePos = SplitNameAndValue(Buffer, " \t="); + if( ValuePos == NULL ) + continue; - KeyName = Buffer; + KeyName = Buffer; - Prepending = NULL; - StringDelimiters = NULL; - Option = GetOptionOfAInfo(Info, + Prepending = NULL; + StringDelimiters = NULL; + Option = GetOptionOfAInfo(Info, KeyName, &Prepending, &StringDelimiters ); - if( Option == NULL ) + if( Option == NULL ) { continue; } @@ -429,33 +429,33 @@ int ConfigRead(ConfigFileInfo *Info) } } - switch( Option->Type ) - { - case TYPE_INT32: - ParseInt32(Option, ValuePos); - break; + switch( Option->Type ) + { + case TYPE_INT32: + ParseInt32(Option, ValuePos); + break; - case TYPE_BOOLEAN: - ParseBoolean(Option, ValuePos); - break; + case TYPE_BOOLEAN: + ParseBoolean(Option, ValuePos); + break; - case TYPE_PATH: + case TYPE_PATH: if( ReadStatus != READ_DONE ) { - break; + break; } if( TrimPath(ValuePos) == NULL ) { - break; - } + break; + } - ExpandPath(ValuePos, sizeof(Buffer) - (ValuePos - Buffer)); - StringDelimiters = ""; - /* No break */ + ExpandPath(ValuePos, sizeof(Buffer) - (ValuePos - Buffer)); + StringDelimiters = ""; + /* No break */ - case TYPE_STRING: - ParseString(Option, + case TYPE_STRING: + ParseString(Option, StringDelimiters == NULL ? Option->Delimiters : StringDelimiters, ValuePos, @@ -465,24 +465,24 @@ int ConfigRead(ConfigFileInfo *Info) Buffer, sizeof(Buffer) ); - break; + break; - default: - break; - } - ++NumOfRead; - } + default: + break; + } + ++NumOfRead; + } - return NumOfRead; + return NumOfRead; } const char *ConfigGetRawString(ConfigFileInfo *Info, char *KeyName) { - ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); + ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); - if( Option != NULL ) - { - StringListIterator sli; + if( Option != NULL ) + { + StringListIterator sli; if( StringListIterator_Init(&sli, &(Option->Holder.str)) != 0 ) { @@ -490,93 +490,93 @@ const char *ConfigGetRawString(ConfigFileInfo *Info, char *KeyName) } return sli.Next(&sli); - } else { - return NULL; - } + } else { + return NULL; + } } StringList *ConfigGetStringList(ConfigFileInfo *Info, char *KeyName) { - ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); - - if( Option != NULL ) - { - if( Option->Holder.str.Count(&(Option->Holder.str)) == 0 ) - { - return NULL; - } else { - return &(Option->Holder.str); - } - } else { - return NULL; - } + ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); + + if( Option != NULL ) + { + if( Option->Holder.str.Count(&(Option->Holder.str)) == 0 ) + { + return NULL; + } else { + return &(Option->Holder.str); + } + } else { + return NULL; + } } int32_t ConfigGetNumberOfStrings(ConfigFileInfo *Info, char *KeyName) { - ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); - - if( Option != NULL ) - { - return Option->Holder.str.Count(&(Option->Holder.str)); - } else { - return 0; - } + ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); + + if( Option != NULL ) + { + return Option->Holder.str.Count(&(Option->Holder.str)); + } else { + return 0; + } } int32_t ConfigGetInt32(ConfigFileInfo *Info, char *KeyName) { - ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); - - if( Option != NULL ) - { - return Option->Holder.INT32; - } else { - return 0; - } + ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); + + if( Option != NULL ) + { + return Option->Holder.INT32; + } else { + return 0; + } } BOOL ConfigGetBoolean(ConfigFileInfo *Info, char *KeyName) { - ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); - - if( Option != NULL ) - { - return Option->Holder.boolean; - } else { - return FALSE; - } + ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); + + if( Option != NULL ) + { + return Option->Holder.boolean; + } else { + return FALSE; + } } /* Won't change the Option's status */ void ConfigSetDefaultValue(ConfigFileInfo *Info, VType Value, char *KeyName) { - ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); - - if( Option != NULL ) - { - switch( Option->Type ) - { - case TYPE_INT32: - Option->Holder.INT32 = Value.INT32; - break; - - case TYPE_BOOLEAN: - Option->Holder.boolean = Value.boolean; - break; - - case TYPE_STRING: - Option->Holder.str.Clear(&(Option->Holder.str)); - Option->Holder.str.Add(&(Option->Holder.str), + ConfigOption *Option = GetOptionOfAInfo(Info, KeyName, NULL, NULL); + + if( Option != NULL ) + { + switch( Option->Type ) + { + case TYPE_INT32: + Option->Holder.INT32 = Value.INT32; + break; + + case TYPE_BOOLEAN: + Option->Holder.boolean = Value.boolean; + break; + + case TYPE_STRING: + Option->Holder.str.Clear(&(Option->Holder.str)); + Option->Holder.str.Add(&(Option->Holder.str), Value.str, Option->Delimiters ); - break; + break; - default: - break; - } - } + default: + break; + } + } } void ConfigFree(ConfigFileInfo *Info) diff --git a/readconfig.h b/readconfig.h index a1f95362..c36c9f82 100755 --- a/readconfig.h +++ b/readconfig.h @@ -18,75 +18,75 @@ */ /* Set the max length of a key name */ -#define KEY_NAME_MAX_SIZE 64 +#define KEY_NAME_MAX_SIZE 64 /* A value must have a type. We just need these types for now. */ typedef enum _OptionType{ TYPE_ALIAS = -1, - TYPE_UNDEFINED = 0, + TYPE_UNDEFINED = 0, - TYPE_INT32, - TYPE_BOOLEAN, - TYPE_PATH, - TYPE_STRING + TYPE_INT32, + TYPE_BOOLEAN, + TYPE_PATH, + TYPE_STRING } OptionType; typedef enum _MultilineStrategy{ - STRATEGY_DEFAULT = 0, - STRATEGY_REPLACE, - STRATEGY_APPEND, - STRATEGY_APPEND_DISCARD_DEFAULT + STRATEGY_DEFAULT = 0, + STRATEGY_REPLACE, + STRATEGY_APPEND, + STRATEGY_APPEND_DISCARD_DEFAULT } MultilineStrategy; typedef union _VType{ - const char *str; - int32_t INT32; - BOOL boolean; + const char *str; + int32_t INT32; + BOOL boolean; } VType; typedef enum _OptionStatus{ - STATUS_DEPRECATED = -2, - STATUS_UNUSED = 0, - STATUS_DEFAULT_VALUE, - STATUS_SPECIAL_VALUE + STATUS_DEPRECATED = -2, + STATUS_UNUSED = 0, + STATUS_DEFAULT_VALUE, + STATUS_SPECIAL_VALUE }OptionStatus; /* An option */ typedef struct _Option{ - /* Designate if this option is used. */ - OptionStatus Status; + /* Designate if this option is used. */ + OptionStatus Status; - MultilineStrategy Strategy; + MultilineStrategy Strategy; - /* Type */ - OptionType Type; + /* Type */ + OptionType Type; - /* Value holder */ - union { - StringList str; - int32_t INT32; - BOOL boolean; + /* Value holder */ + union { + StringList str; + int32_t INT32; + BOOL boolean; - struct { - char *Target; - char *Prepending; - } Aliasing; - } Holder; + struct { + char *Target; + char *Prepending; + } Aliasing; + } Holder; - char *Delimiters; + char *Delimiters; } ConfigOption; /* The exposed type(The infomations about a configuration file) to read options from a configuration file. */ typedef struct _ConfigFileInfo { - /* Static, once inited, never changed. */ - FILE *fp; + /* Static, once inited, never changed. */ + FILE *fp; StringList StrBuffer; - /* An array of all the options. */ - StringChunk Options; + /* An array of all the options. */ + StringChunk Options; } ConfigFileInfo; int ConfigInitInfo(ConfigFileInfo *Info); diff --git a/readline.c b/readline.c index 2b8b530a..a6277561 100755 --- a/readline.c +++ b/readline.c @@ -5,129 +5,129 @@ static BOOL ClearAnnotation(char *str, char mark) { - char *pos = strchr(str, mark); - - if( pos != NULL ) - { - for(--pos; pos >= str && isspace(*pos); --pos); - *(pos + 1) = '\0'; - return TRUE; - } else { - return FALSE; - } + char *pos = strchr(str, mark); + + if( pos != NULL ) + { + for(--pos; pos >= str && isspace(*pos); --pos); + *(pos + 1) = '\0'; + return TRUE; + } else { + return FALSE; + } } static BOOL ReachedLineEnd(FILE *fp, char *str) { - int len = strlen(str); - - if( len != 0 && (str[len - 1] == '\r' || str[len - 1] == '\n') ) - { - return TRUE; - } else { - if( feof(fp) ) - { - return TRUE; - } else { - return FALSE; - } - } + int len = strlen(str); + + if( len != 0 && (str[len - 1] == '\r' || str[len - 1] == '\n') ) + { + return TRUE; + } else { + if( feof(fp) ) + { + return TRUE; + } else { + return FALSE; + } + } } static void EliminateCRLF(char *str) { - ClearAnnotation(str, '\r'); - ClearAnnotation(str, '\n'); + ClearAnnotation(str, '\r'); + ClearAnnotation(str, '\n'); } static void EliminateHeadSpace(char *str) { - char *Home; + char *Home; - for(Home = str; isspace(*Home); ++Home); - if( Home != str ) - { - memmove(str, Home, strlen(Home) + 1); - } + for(Home = str; isspace(*Home); ++Home); + if( Home != str ) + { + memmove(str, Home, strlen(Home) + 1); + } } static void EliminateFootSpace(char *str) { - char *End = str + strlen(str) - 1; + char *End = str + strlen(str) - 1; - if( End >= str ) - { - for(; isspace(*End) && End >= str; --End); - *(End + 1) = '\0'; - } + if( End >= str ) + { + for(; isspace(*End) && End >= str; --End); + *(End + 1) = '\0'; + } } ReadLineStatus ReadLine(FILE *fp, char *Buffer, int BufferSize) { - BOOL ReachedEnd; + BOOL ReachedEnd; START: - ReachedEnd = TRUE; - - if( fgets(Buffer, BufferSize, fp) == NULL ) - { - return READ_FAILED_OR_END; - } else { - ReachedEnd = ReachedLineEnd(fp, Buffer); - } - - if( (ClearAnnotation(Buffer, '#') || ClearAnnotation(Buffer, ';')) != FALSE ) - { - if( ReachedEnd == FALSE ) - { - char BlackHole[128]; - do - { - fgets(BlackHole, sizeof(BlackHole), fp); - ReachedEnd = ReachedLineEnd(fp, BlackHole); - }while( ReachedEnd == FALSE ); - } - - EliminateFootSpace(Buffer); - EliminateHeadSpace(Buffer); - - if( *Buffer == '\0' ) - { - goto START; - } else { - return READ_DONE; - } - - } - - if( ReachedEnd == TRUE ) - { - EliminateCRLF(Buffer); - EliminateFootSpace(Buffer); - EliminateHeadSpace(Buffer); - if( *Buffer == '\0' ) - { - goto START; - } else { - return READ_DONE; - } - } else { - return READ_TRUNCATED; - } + ReachedEnd = TRUE; + + if( fgets(Buffer, BufferSize, fp) == NULL ) + { + return READ_FAILED_OR_END; + } else { + ReachedEnd = ReachedLineEnd(fp, Buffer); + } + + if( (ClearAnnotation(Buffer, '#') || ClearAnnotation(Buffer, ';')) != FALSE ) + { + if( ReachedEnd == FALSE ) + { + char BlackHole[128]; + do + { + fgets(BlackHole, sizeof(BlackHole), fp); + ReachedEnd = ReachedLineEnd(fp, BlackHole); + }while( ReachedEnd == FALSE ); + } + + EliminateFootSpace(Buffer); + EliminateHeadSpace(Buffer); + + if( *Buffer == '\0' ) + { + goto START; + } else { + return READ_DONE; + } + + } + + if( ReachedEnd == TRUE ) + { + EliminateCRLF(Buffer); + EliminateFootSpace(Buffer); + EliminateHeadSpace(Buffer); + if( *Buffer == '\0' ) + { + goto START; + } else { + return READ_DONE; + } + } else { + return READ_TRUNCATED; + } } ReadLineStatus ReadLine_GoToNextLine(FILE *fp) { - ReadLineStatus Status; - char Buffer[128]; + ReadLineStatus Status; + char Buffer[128]; - do - { - Status = ReadLine(fp, Buffer, sizeof(Buffer)); - } - while( Status == READ_TRUNCATED ); + do + { + Status = ReadLine(fp, Buffer, sizeof(Buffer)); + } + while( Status == READ_TRUNCATED ); - return Status; + return Status; } diff --git a/readline.h b/readline.h index d91f01c1..8af55738 100755 --- a/readline.h +++ b/readline.h @@ -5,9 +5,9 @@ typedef enum _ReadLineStatus { - READ_FAILED_OR_END = -1, - READ_DONE = 0, - READ_TRUNCATED, + READ_FAILED_OR_END = -1, + READ_DONE = 0, + READ_TRUNCATED, } ReadLineStatus; ReadLineStatus ReadLine(FILE *fp, char *Buffer, int BufferSize); diff --git a/rwlock.h b/rwlock.h index c6f86caf..8467013c 100755 --- a/rwlock.h +++ b/rwlock.h @@ -4,80 +4,80 @@ #include "common.h" #ifdef WIN32 - #ifdef WIN64 + #ifdef WIN64 /* - #ifndef InitializeSRWLock - typedef struct _RWLock { - PVOID Ptr; - } RWLock; - #else - typedef SRWLOCK RWLock; - #endif + #ifndef InitializeSRWLock + typedef struct _RWLock { + PVOID Ptr; + } RWLock; + #else + typedef SRWLOCK RWLock; + #endif */ typedef SRWLOCK RWLock; - #else /* WIN64 */ - typedef CRITICAL_SECTION RWLock; - #endif /* WIN64 */ + #else /* WIN64 */ + typedef CRITICAL_SECTION RWLock; + #endif /* WIN64 */ #else /* WIN32 */ #ifdef HAVE_PTHREAD_RWLOCK_INIT - typedef pthread_rwlock_t RWLock; + typedef pthread_rwlock_t RWLock; #else /* HAVE_PTHREAD_RWLOCK_INIT */ - typedef pthread_mutex_t RWLock; + typedef pthread_mutex_t RWLock; #endif /* HAVE_PTHREAD_RWLOCK_INIT */ #endif /* WIN32 */ #ifdef WIN32 - #ifdef WIN64 + #ifdef WIN64 /* - #ifndef InitializeSRWLock + #ifndef InitializeSRWLock - VOID WINAPI InitializeSRWLock(RWLock *SRWLock); - VOID WINAPI AcquireSRWLockShared(RWLock *SRWLock); - VOID WINAPI AcquireSRWLockExclusive(RWLock *SRWLock); - VOID WINAPI ReleaseSRWLockShared(RWLock *SRWLock); - VOID WINAPI ReleaseSRWLockExclusive(RWLock *SRWLock); + VOID WINAPI InitializeSRWLock(RWLock *SRWLock); + VOID WINAPI AcquireSRWLockShared(RWLock *SRWLock); + VOID WINAPI AcquireSRWLockExclusive(RWLock *SRWLock); + VOID WINAPI ReleaseSRWLockShared(RWLock *SRWLock); + VOID WINAPI ReleaseSRWLockExclusive(RWLock *SRWLock); - #endif - */ + #endif + */ - #define RWLock_Init(l) InitializeSRWLock(&(l)) - #define RWLock_RdLock(l) AcquireSRWLockShared(&(l)) - #define RWLock_WrLock(l) AcquireSRWLockExclusive(&(l)) - #define RWLock_UnRLock(l) ReleaseSRWLockShared(&(l)) - #define RWLock_UnWLock(l) ReleaseSRWLockExclusive(&(l)) - #define RWLock_Destroy(l) + #define RWLock_Init(l) InitializeSRWLock(&(l)) + #define RWLock_RdLock(l) AcquireSRWLockShared(&(l)) + #define RWLock_WrLock(l) AcquireSRWLockExclusive(&(l)) + #define RWLock_UnRLock(l) ReleaseSRWLockShared(&(l)) + #define RWLock_UnWLock(l) ReleaseSRWLockExclusive(&(l)) + #define RWLock_Destroy(l) - #else /* WIN64 */ + #else /* WIN64 */ - #define RWLock_Init(l) CRITICAL_SECTION_INIT((l), 1024) - #define RWLock_RdLock(l) ENTER_CRITICAL_SECTION(l) - #define RWLock_WrLock(l) ENTER_CRITICAL_SECTION(l) - #define RWLock_UnRLock(l) LEAVE_CRITICAL_SECTION(l) - #define RWLock_UnWLock(l) LEAVE_CRITICAL_SECTION(l) - #define RWLock_Destroy(l) DELETE_CRITICAL_SECTION(l) + #define RWLock_Init(l) CRITICAL_SECTION_INIT((l), 1024) + #define RWLock_RdLock(l) ENTER_CRITICAL_SECTION(l) + #define RWLock_WrLock(l) ENTER_CRITICAL_SECTION(l) + #define RWLock_UnRLock(l) LEAVE_CRITICAL_SECTION(l) + #define RWLock_UnWLock(l) LEAVE_CRITICAL_SECTION(l) + #define RWLock_Destroy(l) DELETE_CRITICAL_SECTION(l) - #endif /* WIN64 */ + #endif /* WIN64 */ #else /* WIN32 */ - #ifdef HAVE_PTHREAD_RWLOCK_INIT - #define RWLock_Init(l) pthread_rwlock_init(&(l), NULL) - #define RWLock_RdLock(l) pthread_rwlock_rdlock(&(l)) - #define RWLock_WrLock(l) pthread_rwlock_wrlock(&(l)) - #define RWLock_UnRLock(l) pthread_rwlock_unlock(&(l)) - #define RWLock_UnWLock(l) pthread_rwlock_unlock(&(l)) - #define RWLock_Destroy(l) pthread_rwlock_destroy(&(l)) - #else - #define RWLock_Init(l) (pthread_mutex_init(&(l), NULL)) - #define RWLock_RdLock(l) (pthread_mutex_lock(&(l))) - #define RWLock_WrLock(l) (pthread_mutex_lock(&(l))) - #define RWLock_UnRLock(l) (pthread_mutex_unlock(&(l))) - #define RWLock_UnWLock(l) (pthread_mutex_unlock(&(l))) - #define RWLock_Destroy(l) (pthread_mutex_destroy(&(l))) - #endif + #ifdef HAVE_PTHREAD_RWLOCK_INIT + #define RWLock_Init(l) pthread_rwlock_init(&(l), NULL) + #define RWLock_RdLock(l) pthread_rwlock_rdlock(&(l)) + #define RWLock_WrLock(l) pthread_rwlock_wrlock(&(l)) + #define RWLock_UnRLock(l) pthread_rwlock_unlock(&(l)) + #define RWLock_UnWLock(l) pthread_rwlock_unlock(&(l)) + #define RWLock_Destroy(l) pthread_rwlock_destroy(&(l)) + #else + #define RWLock_Init(l) (pthread_mutex_init(&(l), NULL)) + #define RWLock_RdLock(l) (pthread_mutex_lock(&(l))) + #define RWLock_WrLock(l) (pthread_mutex_lock(&(l))) + #define RWLock_UnRLock(l) (pthread_mutex_unlock(&(l))) + #define RWLock_UnWLock(l) (pthread_mutex_unlock(&(l))) + #define RWLock_Destroy(l) (pthread_mutex_destroy(&(l))) + #endif #endif /* WIN32 */ #endif // RWLOCK_H_INCLUDED diff --git a/simpleht.c b/simpleht.c index 2e8bd690..d4247ac4 100755 --- a/simpleht.c +++ b/simpleht.c @@ -2,180 +2,180 @@ #include "simpleht.h" typedef struct _Sht_Slot{ - int32_t Next; + int32_t Next; } Sht_Slot; static const Sht_Slot EmptySlot = {-1}; int SimpleHT_Init(SimpleHT *ht, int DataLength, size_t MaxLoadFactor, uint32_t (*HashFunction)(const char *, uint32_t)) { - int loop; + int loop; if( Array_Init(&(ht->Slots), sizeof(Sht_Slot), 7, FALSE, NULL) != 0 ) { - return -1; + return -1; } - for( loop = 0; loop != 7; ++loop ) - { - Array_PushBack(&(ht->Slots), &EmptySlot, NULL); - } + for( loop = 0; loop != 7; ++loop ) + { + Array_PushBack(&(ht->Slots), &EmptySlot, NULL); + } if( Array_Init(&(ht->Nodes), sizeof(Sht_NodeHead) + DataLength, 0, FALSE, NULL) != 0 ) { - return -2; + return -2; } - ht->MaxLoadFactor = MaxLoadFactor; - ht->LeftSpace = 7 * MaxLoadFactor; - ht->HashFunction = HashFunction; + ht->MaxLoadFactor = MaxLoadFactor; + ht->LeftSpace = 7 * MaxLoadFactor; + ht->HashFunction = HashFunction; - return 0; + return 0; } static int SimpleHT_AddToSlot(SimpleHT *ht, Sht_NodeHead *Node, int NodeSubscript) { - int NumberOfSlots = Array_GetUsed(&(ht->Slots)); - Sht_Slot *TheSlot; + int NumberOfSlots = Array_GetUsed(&(ht->Slots)); + Sht_Slot *TheSlot; - TheSlot = Array_GetBySubscript(&(ht->Slots), Node->HashValue % NumberOfSlots); - if( TheSlot == NULL ) - { - return -1; - } + TheSlot = Array_GetBySubscript(&(ht->Slots), Node->HashValue % NumberOfSlots); + if( TheSlot == NULL ) + { + return -1; + } - Node->Next = TheSlot->Next; - TheSlot->Next = NodeSubscript; + Node->Next = TheSlot->Next; + TheSlot->Next = NodeSubscript; - return 0; + return 0; } static int SimpleHT_Expand(SimpleHT *ht) { - int NumberOfSlots_Old = Array_GetUsed(&(ht->Slots)); - int NumberOfNodes = Array_GetUsed(&(ht->Nodes)); - Sht_NodeHead *nh = NULL; - int loop; - - for( loop = 0; loop < NumberOfSlots_Old; ++loop ) - { - if( Array_PushBack(&(ht->Slots), &EmptySlot, NULL) < 0 ) - { - return -1; - } - } + int NumberOfSlots_Old = Array_GetUsed(&(ht->Slots)); + int NumberOfNodes = Array_GetUsed(&(ht->Nodes)); + Sht_NodeHead *nh = NULL; + int loop; + + for( loop = 0; loop < NumberOfSlots_Old; ++loop ) + { + if( Array_PushBack(&(ht->Slots), &EmptySlot, NULL) < 0 ) + { + return -1; + } + } memset(ht->Slots.Data, -1, NumberOfSlots_Old * ht->Slots.DataLength); - for( loop = 0; loop < NumberOfNodes; ++loop ) - { - nh = Array_GetBySubscript(&(ht->Nodes), loop); - SimpleHT_AddToSlot(ht, nh, loop); - } + for( loop = 0; loop < NumberOfNodes; ++loop ) + { + nh = Array_GetBySubscript(&(ht->Nodes), loop); + SimpleHT_AddToSlot(ht, nh, loop); + } - return 0; + return 0; } const char *SimpleHT_Add(SimpleHT *ht, const char *Key, int KeyLength, const char *Data, uint32_t *HashValue) { - Sht_NodeHead *New; - int NewSubscript; + Sht_NodeHead *New; + int NewSubscript; - if( ht->LeftSpace == 0 ) - { - int NumberOfSlots_Old = Array_GetUsed(&(ht->Slots)); + if( ht->LeftSpace == 0 ) + { + int NumberOfSlots_Old = Array_GetUsed(&(ht->Slots)); - if( SimpleHT_Expand(ht) != 0 ) - { - return NULL; - } + if( SimpleHT_Expand(ht) != 0 ) + { + return NULL; + } - ht->LeftSpace = NumberOfSlots_Old * ht->MaxLoadFactor; - } + ht->LeftSpace = NumberOfSlots_Old * ht->MaxLoadFactor; + } - NewSubscript = Array_PushBack(&(ht->Nodes), NULL, NULL); - if( NewSubscript < 0 ) - { - return NULL; - } + NewSubscript = Array_PushBack(&(ht->Nodes), NULL, NULL); + if( NewSubscript < 0 ) + { + return NULL; + } - New = Array_GetBySubscript(&(ht->Nodes), NewSubscript); + New = Array_GetBySubscript(&(ht->Nodes), NewSubscript); - if( HashValue == NULL ) - { - New->HashValue = (ht->HashFunction)(Key, KeyLength); - } else { - New->HashValue = *HashValue; - } + if( HashValue == NULL ) + { + New->HashValue = (ht->HashFunction)(Key, KeyLength); + } else { + New->HashValue = *HashValue; + } - memcpy(New + 1, Data, ht->Nodes.DataLength - sizeof(Sht_NodeHead)); + memcpy(New + 1, Data, ht->Nodes.DataLength - sizeof(Sht_NodeHead)); - SimpleHT_AddToSlot(ht, New, NewSubscript); + SimpleHT_AddToSlot(ht, New, NewSubscript); - --(ht->LeftSpace); + --(ht->LeftSpace); - return (const char *)(New + 1); + return (const char *)(New + 1); } const char *SimpleHT_Find(SimpleHT *ht, const char *Key, int KeyLength, uint32_t *HashValue, const char *Start) { - int NumberOfSlots = Array_GetUsed(&(ht->Slots)); - int SlotNumber; - Sht_Slot *TheSlot; - Sht_NodeHead *Node; - - if( NumberOfSlots <= 0 ) - { - return NULL; - } - - if( Start != NULL ) - { - Node = Array_GetBySubscript(&(ht->Nodes), (((Sht_NodeHead *)Start) - 1)->Next); - } else { - if( HashValue == NULL ) - { - SlotNumber = (ht->HashFunction)(Key, KeyLength) % NumberOfSlots; - } else { - SlotNumber = (*HashValue) % NumberOfSlots; - } - - TheSlot = Array_GetBySubscript(&(ht->Slots), SlotNumber); - if( TheSlot == NULL ) - { - return NULL; - } - - Node = Array_GetBySubscript(&(ht->Nodes), TheSlot->Next); - } - - if( Node == NULL ) - { - return NULL; - } - - return (const char *)(Node + 1); + int NumberOfSlots = Array_GetUsed(&(ht->Slots)); + int SlotNumber; + Sht_Slot *TheSlot; + Sht_NodeHead *Node; + + if( NumberOfSlots <= 0 ) + { + return NULL; + } + + if( Start != NULL ) + { + Node = Array_GetBySubscript(&(ht->Nodes), (((Sht_NodeHead *)Start) - 1)->Next); + } else { + if( HashValue == NULL ) + { + SlotNumber = (ht->HashFunction)(Key, KeyLength) % NumberOfSlots; + } else { + SlotNumber = (*HashValue) % NumberOfSlots; + } + + TheSlot = Array_GetBySubscript(&(ht->Slots), SlotNumber); + if( TheSlot == NULL ) + { + return NULL; + } + + Node = Array_GetBySubscript(&(ht->Nodes), TheSlot->Next); + } + + if( Node == NULL ) + { + return NULL; + } + + return (const char *)(Node + 1); } const char *SimpleHT_Enum(SimpleHT *ht, int32_t *Start) { - Array *Nodes = &(ht->Nodes); - Sht_NodeHead *Node; - - Node = Array_GetBySubscript(Nodes, *Start); - - if( Node != NULL ) - { - ++(*Start); - return (const char *)(Node + 1); - } else { - return NULL; - } + Array *Nodes = &(ht->Nodes); + Sht_NodeHead *Node; + + Node = Array_GetBySubscript(Nodes, *Start); + + if( Node != NULL ) + { + ++(*Start); + return (const char *)(Node + 1); + } else { + return NULL; + } } void SimpleHT_Free(SimpleHT *ht) { - Array_Free(&(ht->Slots)); - Array_Free(&(ht->Nodes)); + Array_Free(&(ht->Slots)); + Array_Free(&(ht->Nodes)); } diff --git a/simpleht.h b/simpleht.h index 2c42ee17..2ce9a729 100755 --- a/simpleht.h +++ b/simpleht.h @@ -4,18 +4,18 @@ #include "array.h" typedef struct _Sht_NodeHead{ - int32_t Next; - uint32_t HashValue; + int32_t Next; + uint32_t HashValue; } Sht_NodeHead; typedef struct _SimpleHT { - Array Slots; - Array Nodes; + Array Slots; + Array Nodes; - size_t MaxLoadFactor; - size_t LeftSpace; + size_t MaxLoadFactor; + size_t LeftSpace; - uint32_t (*HashFunction)(const char *, uint32_t); + uint32_t (*HashFunction)(const char *, uint32_t); } SimpleHT; diff --git a/socketpool.c b/socketpool.c index dd82e413..660401d4 100755 --- a/socketpool.c +++ b/socketpool.c @@ -8,9 +8,9 @@ static int SocketPool_Add(SocketPool *sp, int DataLength ) { - SocketUnit su; + SocketUnit su; - su.Sock = Sock; + su.Sock = Sock; if( Data != NULL ) { @@ -20,12 +20,12 @@ static int SocketPool_Add(SocketPool *sp, su.Data = NULL; } - if( sp->t.Add(&(sp->t), &su) == NULL ) - { - return -27; - } + if( sp->t.Add(&(sp->t), &su) == NULL ) + { + return -27; + } - return 0; + return 0; } static int SocketPool_Del(SocketPool *sp, SOCKET Sock) @@ -117,7 +117,7 @@ static void SocketPool_Free(SocketPool *sp, BOOL CloseAllSocket) static int Compare(const SocketUnit *_1, const SocketUnit *_2) { - return (int)(_1->Sock) - (int)(_2->Sock); + return (int)(_1->Sock) - (int)(_2->Sock); } int SocketPool_Init(SocketPool *sp) diff --git a/socketpool.h b/socketpool.h index 8e4b5306..f0252ef5 100755 --- a/socketpool.h +++ b/socketpool.h @@ -7,8 +7,8 @@ #include "common.h" typedef struct _SocketUnit { - SOCKET Sock; - const char *Data; + SOCKET Sock; + const char *Data; } SocketUnit; typedef struct _SocketPool SocketPool; @@ -18,7 +18,7 @@ struct _SocketPool{ Bst t; StableBuffer d; - /* public */ + /* public */ int (*Add)(SocketPool *sp, SOCKET Sock, const void *Data, diff --git a/statichosts.c b/statichosts.c index 4f232eb3..7d93d390 100755 --- a/statichosts.c +++ b/statichosts.c @@ -2,44 +2,44 @@ #include "statichosts.h" #include "logs.h" -static HostsContainer MainStaticContainer; +static HostsContainer MainStaticContainer; static BOOL Inited = FALSE; int StaticHosts_Init(ConfigFileInfo *ConfigInfo) { - StringList *AppendHosts = ConfigGetStringList(ConfigInfo, "AppendHosts"); - StringListIterator sli; + StringList *AppendHosts = ConfigGetStringList(ConfigInfo, "AppendHosts"); + StringListIterator sli; - const char *Itr; + const char *Itr; - if( HostsContainer_Init(&MainStaticContainer) != 0 ) - { - return -17; - } + if( HostsContainer_Init(&MainStaticContainer) != 0 ) + { + return -17; + } - if( AppendHosts == NULL ) - { - return -22; - } + if( AppendHosts == NULL ) + { + return -22; + } - if( StringListIterator_Init(&sli, AppendHosts) != 0 ) + if( StringListIterator_Init(&sli, AppendHosts) != 0 ) { return -27; } - Itr = sli.Next(&sli); - while( Itr != NULL ) - { + Itr = sli.Next(&sli); + while( Itr != NULL ) + { MainStaticContainer.Load(&MainStaticContainer, Itr); - Itr = sli.Next(&sli); - } + Itr = sli.Next(&sli); + } - Inited = TRUE; + Inited = TRUE; - INFO("Loading Appendhosts completed.\n"); + INFO("Loading Appendhosts completed.\n"); - return 0; + return 0; } int StaticHosts_GetCName(const char *Domain, char *Buffer) diff --git a/stringchunk.c b/stringchunk.c index bbe2220c..e0115ea7 100755 --- a/stringchunk.c +++ b/stringchunk.c @@ -3,60 +3,60 @@ #include "utils.h" typedef struct _EntryForString{ - const char *str; - void *Data; + const char *str; + void *Data; } EntryForString; int StringChunk_Init(StringChunk *dl, StringList *List) { - if( dl == NULL ) - { - return 0; - } - - if( SimpleHT_Init(&(dl->List_Pos), sizeof(EntryForString), 5, HASH) != 0 ) - { - return -1; - } - - if( Array_Init(&(dl->List_W_Pos), sizeof(EntryForString), 0, FALSE, NULL) != 0 ) - { - SimpleHT_Free(&(dl->List_Pos)); - return -2; - } - - if( StableBuffer_Init(&(dl->AdditionalDataChunk)) != 0 ) - { - SimpleHT_Free(&(dl->List_Pos)); - Array_Free(&(dl->List_W_Pos)); - return -3; - } - - /* Whether to use external `StringList' to store strings. */ - if( List == NULL ) - { - dl->List = SafeMalloc(sizeof(StringList)); - if( dl->List == NULL ) - { - return -4; - } - - if( StringList_Init(dl->List, NULL, NULL) != 0 ) - { - return -5; - } - } else { - dl->List = List; - } - - return 0; + if( dl == NULL ) + { + return 0; + } + + if( SimpleHT_Init(&(dl->List_Pos), sizeof(EntryForString), 5, HASH) != 0 ) + { + return -1; + } + + if( Array_Init(&(dl->List_W_Pos), sizeof(EntryForString), 0, FALSE, NULL) != 0 ) + { + SimpleHT_Free(&(dl->List_Pos)); + return -2; + } + + if( StableBuffer_Init(&(dl->AdditionalDataChunk)) != 0 ) + { + SimpleHT_Free(&(dl->List_Pos)); + Array_Free(&(dl->List_W_Pos)); + return -3; + } + + /* Whether to use external `StringList' to store strings. */ + if( List == NULL ) + { + dl->List = SafeMalloc(sizeof(StringList)); + if( dl->List == NULL ) + { + return -4; + } + + if( StringList_Init(dl->List, NULL, NULL) != 0 ) + { + return -5; + } + } else { + dl->List = List; + } + + return 0; } -int StringChunk_Add(StringChunk *dl, - const char *Str, - const void *AdditionalData, - int LengthOfAdditionalData /* The length will not be stored. */ - ) +int StringChunk_Add(StringChunk *dl, + const char *Str, + const void *AdditionalData, + int LengthOfAdditionalData /* The length will not be stored. */ + ) { StableBuffer *sb; StringList *sl; @@ -64,271 +64,271 @@ int StringChunk_Add(StringChunk *dl, SimpleHT *nl; Array *wl; - EntryForString NewEntry; + EntryForString NewEntry; - if( dl == NULL ) - { - return FALSE; - } + if( dl == NULL ) + { + return FALSE; + } sb = &(dl->AdditionalDataChunk); sl = dl->List; nl = &(dl->List_Pos); wl = &(dl->List_W_Pos); - if( AdditionalData != NULL && LengthOfAdditionalData > 0 ) - { - NewEntry.Data = sb->Add(sb, + if( AdditionalData != NULL && LengthOfAdditionalData > 0 ) + { + NewEntry.Data = sb->Add(sb, AdditionalData, LengthOfAdditionalData, TRUE ); - if( NewEntry.Data == NULL ) + if( NewEntry.Data == NULL ) { return -1; } - } else { - NewEntry.Data = NULL; - } - - NewEntry.str = sl->Add(sl, Str, NULL); - if( NewEntry.str == NULL ) - { - return -2; - } - - if( ContainWildCard(Str) ) - { - if( Array_PushBack(wl, &NewEntry, NULL) < 0 ) + } else { + NewEntry.Data = NULL; + } + + NewEntry.str = sl->Add(sl, Str, NULL); + if( NewEntry.str == NULL ) + { + return -2; + } + + if( ContainWildCard(Str) ) + { + if( Array_PushBack(wl, &NewEntry, NULL) < 0 ) { return -3; } - } else { - if( SimpleHT_Add(nl, Str, 0, (const char *)&NewEntry, NULL) == NULL ) + } else { + if( SimpleHT_Add(nl, Str, 0, (const char *)&NewEntry, NULL) == NULL ) { return -4; } - } + } - return 0; + return 0; } -int StringChunk_Add_Domain(StringChunk *dl, - const char *Domain, - const void *AdditionalData, - int LengthOfAdditionalData /* The length will not be stored. */ - ) +int StringChunk_Add_Domain(StringChunk *dl, + const char *Domain, + const void *AdditionalData, + int LengthOfAdditionalData /* The length will not be stored. */ + ) { - if( *Domain == '.' ) - { - ++Domain; - } + if( *Domain == '.' ) + { + ++Domain; + } - return StringChunk_Add(dl, Domain, AdditionalData, LengthOfAdditionalData); + return StringChunk_Add(dl, Domain, AdditionalData, LengthOfAdditionalData); } -BOOL StringChunk_Match_NoWildCard(StringChunk *dl, - const char *Str, - uint32_t *HashValue, - void **Data - ) +BOOL StringChunk_Match_NoWildCard(StringChunk *dl, + const char *Str, + uint32_t *HashValue, + void **Data + ) { SimpleHT *nl; - EntryForString *FoundEntry; + EntryForString *FoundEntry; - const char *FoundString; + const char *FoundString; - if( dl == NULL ) - { - return FALSE; - } + if( dl == NULL ) + { + return FALSE; + } nl = &(dl->List_Pos); - FoundEntry = (EntryForString *)SimpleHT_Find(nl, Str, 0, HashValue, NULL); - while( FoundEntry != NULL ) - { - FoundString = FoundEntry->str; - if( strcmp(FoundString, Str) == 0 ) - { - if( Data != NULL ) - { - *Data = (void *)(FoundEntry->Data); - } + FoundEntry = (EntryForString *)SimpleHT_Find(nl, Str, 0, HashValue, NULL); + while( FoundEntry != NULL ) + { + FoundString = FoundEntry->str; + if( strcmp(FoundString, Str) == 0 ) + { + if( Data != NULL ) + { + *Data = (void *)(FoundEntry->Data); + } - return TRUE; - } + return TRUE; + } - FoundEntry = (EntryForString *)SimpleHT_Find(nl, Str, 0, HashValue, (const char *)FoundEntry); - } + FoundEntry = (EntryForString *)SimpleHT_Find(nl, Str, 0, HashValue, (const char *)FoundEntry); + } - return FALSE; + return FALSE; } -BOOL StringChunk_Match_OnlyWildCard(StringChunk *dl, - const char *Str, - void **Data - ) +BOOL StringChunk_Match_OnlyWildCard(StringChunk *dl, + const char *Str, + void **Data + ) { Array *wl; - EntryForString *FoundEntry; + EntryForString *FoundEntry; - int loop; + int loop; - if( dl == NULL ) - { - return FALSE; - } + if( dl == NULL ) + { + return FALSE; + } wl = &(dl->List_W_Pos); - for( loop = 0; loop != Array_GetUsed(wl); ++loop ) - { - FoundEntry = (EntryForString *)Array_GetBySubscript(wl, loop); - if( FoundEntry != NULL ) - { + for( loop = 0; loop != Array_GetUsed(wl); ++loop ) + { + FoundEntry = (EntryForString *)Array_GetBySubscript(wl, loop); + if( FoundEntry != NULL ) + { const char *FoundString = FoundEntry->str; - if( WILDCARD_MATCH(FoundString, Str) == WILDCARD_MATCHED ) - { - if( Data != NULL ) - { - *Data = (void *)(FoundEntry->Data); - } - return TRUE; - } - - } else { - return FALSE; - } - } - - return FALSE; + if( WILDCARD_MATCH(FoundString, Str) == WILDCARD_MATCHED ) + { + if( Data != NULL ) + { + *Data = (void *)(FoundEntry->Data); + } + return TRUE; + } + + } else { + return FALSE; + } + } + + return FALSE; } BOOL StringChunk_Match(StringChunk *dl, const char *Str, uint32_t *HashValue, void **Data) { - return (StringChunk_Match_NoWildCard(dl, Str, HashValue, Data) || - StringChunk_Match_OnlyWildCard(dl, Str, Data)); + return (StringChunk_Match_NoWildCard(dl, Str, HashValue, Data) || + StringChunk_Match_OnlyWildCard(dl, Str, Data)); } -static BOOL StringChunk_Match_WildCard_Exacly(StringChunk *dl, - const char *Str, - void **Data +static BOOL StringChunk_Match_WildCard_Exacly(StringChunk *dl, + const char *Str, + void **Data ) { Array *wl; - EntryForString *FoundEntry; + EntryForString *FoundEntry; - int loop; + int loop; - if( dl == NULL ) - { - return FALSE; - } + if( dl == NULL ) + { + return FALSE; + } wl = &(dl->List_W_Pos); - for( loop = 0; loop != Array_GetUsed(wl); ++loop ) - { - FoundEntry = (EntryForString *)Array_GetBySubscript(wl, loop); - if( FoundEntry != NULL ) - { + for( loop = 0; loop != Array_GetUsed(wl); ++loop ) + { + FoundEntry = (EntryForString *)Array_GetBySubscript(wl, loop); + if( FoundEntry != NULL ) + { const char *FoundString = FoundEntry->str; - if( strcmp(Str, FoundString) == 0 ) - { - if( Data != NULL ) - { - *Data = (void *)(FoundEntry->Data); - } - return TRUE; - } - - } else { - return FALSE; - } - } - - return FALSE; + if( strcmp(Str, FoundString) == 0 ) + { + if( Data != NULL ) + { + *Data = (void *)(FoundEntry->Data); + } + return TRUE; + } + + } else { + return FALSE; + } + } + + return FALSE; } BOOL StringChunk_Match_Exacly(StringChunk *dl, const char *Str, uint32_t *HashValue, void **Data) { - return (StringChunk_Match_NoWildCard(dl, Str, HashValue, Data) || - StringChunk_Match_WildCard_Exacly(dl, Str, Data)); + return (StringChunk_Match_NoWildCard(dl, Str, HashValue, Data) || + StringChunk_Match_WildCard_Exacly(dl, Str, Data)); } BOOL StringChunk_Domain_Match_NoWildCard(StringChunk *dl, const char *Domain, uint32_t *HashValue, void **Data) { - if( StringChunk_Match_NoWildCard(dl, Domain, HashValue, Data) == TRUE ) - { - return TRUE; - } + if( StringChunk_Match_NoWildCard(dl, Domain, HashValue, Data) == TRUE ) + { + return TRUE; + } - Domain = strchr(Domain + 1, '.'); + Domain = strchr(Domain + 1, '.'); - while( Domain != NULL ) - { - if( StringChunk_Match_NoWildCard(dl, Domain + 1, NULL, Data) == TRUE ) - { - return TRUE; - } + while( Domain != NULL ) + { + if( StringChunk_Match_NoWildCard(dl, Domain + 1, NULL, Data) == TRUE ) + { + return TRUE; + } - Domain = strchr(Domain + 1, '.'); - } + Domain = strchr(Domain + 1, '.'); + } - return FALSE; + return FALSE; } BOOL StringChunk_Domain_Match(StringChunk *dl, const char *Domain, uint32_t *HashValue, void **Data) { - if( dl == NULL ) - { - return FALSE; - } + if( dl == NULL ) + { + return FALSE; + } - return (StringChunk_Domain_Match_NoWildCard(dl, Domain, HashValue, Data) || - StringChunk_Match_OnlyWildCard(dl, Domain, Data) ); + return (StringChunk_Domain_Match_NoWildCard(dl, Domain, HashValue, Data) || + StringChunk_Match_OnlyWildCard(dl, Domain, Data) ); } /* Start by 0 */ const char *StringChunk_Enum_NoWildCard(StringChunk *dl, int32_t *Start, void **Data) { - EntryForString *Result; + EntryForString *Result; - Result = (EntryForString *)SimpleHT_Enum(&(dl->List_Pos), Start); - if( Result == NULL ) - { - if( Data != NULL ) - { - *Data = NULL; - } + Result = (EntryForString *)SimpleHT_Enum(&(dl->List_Pos), Start); + if( Result == NULL ) + { + if( Data != NULL ) + { + *Data = NULL; + } - return NULL; - } + return NULL; + } - if( Data != NULL ) - { - *Data = (void *)Result->Data; - } + if( Data != NULL ) + { + *Data = (void *)Result->Data; + } - return Result->str; + return Result->str; } void StringChunk_Free(StringChunk *dl, BOOL FreeStringList) { - SimpleHT_Free(&(dl->List_Pos)); - Array_Free(&(dl->List_W_Pos)); - dl->AdditionalDataChunk.Free(&(dl->AdditionalDataChunk)); - - if( FreeStringList == TRUE ) - { - dl->List->Free(dl->List); - SafeFree(dl->List); - } + SimpleHT_Free(&(dl->List_Pos)); + Array_Free(&(dl->List_W_Pos)); + dl->AdditionalDataChunk.Free(&(dl->AdditionalDataChunk)); + + if( FreeStringList == TRUE ) + { + dl->List->Free(dl->List); + SafeFree(dl->List); + } } int InitChunk(StringChunk **dl) diff --git a/stringlist.c b/stringlist.c index 0743e867..aac6be12 100755 --- a/stringlist.c +++ b/stringlist.c @@ -4,26 +4,26 @@ static int Divide(char *Str, const char *Delimiters) { - int Count = 0; - char *Itr; + int Count = 0; + char *Itr; - if( Delimiters == NULL ) + if( Delimiters == NULL ) { return 1; } - Itr = strpbrk(Str, Delimiters); - while( Itr != NULL ) + Itr = strpbrk(Str, Delimiters); + while( Itr != NULL ) { *Itr = '\0'; ++Itr; - ++Count; + ++Count; - Itr = strpbrk(Itr, Delimiters); + Itr = strpbrk(Itr, Delimiters); } - return Count + 1; + return Count + 1; } static int StringList_Count(StringList *s) @@ -266,7 +266,7 @@ int StringList_Init(__in StringList *s, { StableBuffer *sb; - if( s == NULL ) + if( s == NULL ) { return -1; } @@ -287,8 +287,8 @@ int StringList_Init(__in StringList *s, s->Clear = StringList_Clear; s->Free = StringList_Free; - if( ori != NULL ) - { + if( ori != NULL ) + { void *Here = sb ->Add(sb, ori, strlen(ori) + 1, FALSE); if( Here == NULL ) { @@ -296,8 +296,8 @@ int StringList_Init(__in StringList *s, return -3; } - Divide(Here, Delimiters); - } + Divide(Here, Delimiters); + } return 0; } diff --git a/tcpm.c b/tcpm.c index c96eb5da..490f34eb 100755 --- a/tcpm.c +++ b/tcpm.c @@ -31,7 +31,7 @@ static SOCKET TcpM_Connect(struct sockaddr **ServerAddressesList, # define NUMBER_OF_SOCKETS 5 #ifdef WIN32 - PTimer t; + PTimer t; #endif SocketPuller p; @@ -48,38 +48,38 @@ static SOCKET TcpM_Connect(struct sockaddr **ServerAddressesList, INFO("Connecting to %s ...\n", Type); #ifdef WIN32 - PTimer_Start(&t); + PTimer_Start(&t); #endif for( i = 0; i < NUMBER_OF_SOCKETS; ++i ) { SOCKET s; - if( ServerAddressesList[i] == NULL ) - { - break; - } + if( ServerAddressesList[i] == NULL ) + { + break; + } - s = socket(FamiliesList[i], SOCK_STREAM, IPPROTO_TCP); + s = socket(FamiliesList[i], SOCK_STREAM, IPPROTO_TCP); if( s == INVALID_SOCKET ) { - continue; + continue; } SetSocketNonBlock(s, TRUE); - if( connect(s, + if( connect(s, ServerAddressesList[i], GetAddressLength(FamiliesList[i]) ) != 0 ) - { - if( GET_LAST_ERROR() != CONNECT_FUNCTION_BLOCKED ) - { - CLOSE_SOCKET(s); - continue; - } - } + { + if( GET_LAST_ERROR() != CONNECT_FUNCTION_BLOCKED ) + { + CLOSE_SOCKET(s); + continue; + } + } p.Add(&p, s, NULL, 0); } @@ -121,8 +121,8 @@ static int TcpM_SendWrapper(SOCKET Sock, const char *Start, int Length) { #define DEFAULT_TIME_OUT__SEND 2000 /* ms */ while( send(Sock, Start, Length, MSG_NOSIGNAL) != Length ) - { - int LastError = GET_LAST_ERROR(); + { + int LastError = GET_LAST_ERROR(); if( FatalErrorDecideding(LastError) != 0 || !SocketIsWritable(Sock, DEFAULT_TIME_OUT__SEND) ) @@ -133,17 +133,17 @@ static int TcpM_SendWrapper(SOCKET Sock, const char *Start, int Length) } #undef DEFAULT_TIME_OUT__SEND - return Length; + return Length; } static int TcpM_RecvWrapper(SOCKET Sock, char *Buffer, int BufferSize) { #define DEFAULT_TIME_OUT__RECV 2000 /* ms */ - int Recvlength; + int Recvlength; - while( (Recvlength = recv(Sock, Buffer, BufferSize, 0)) < 0 ) - { - int LastError = GET_LAST_ERROR(); + while( (Recvlength = recv(Sock, Buffer, BufferSize, 0)) < 0 ) + { + int LastError = GET_LAST_ERROR(); if( FatalErrorDecideding(LastError) != 0 || !SocketIsStillReadable(Sock, DEFAULT_TIME_OUT__RECV) ) @@ -151,9 +151,9 @@ static int TcpM_RecvWrapper(SOCKET Sock, char *Buffer, int BufferSize) ShowSocketError("Receiving from TCP server or proxy failed", LastError); return (-1) * LastError; } - } + } #undef DEFAULT_TIME_OUT__RECV - return Recvlength; + return Recvlength; } static int TcpM_ProxyPreparation(SOCKET Sock, @@ -167,34 +167,34 @@ static int TcpM_ProxyPreparation(SOCKET Sock, unsigned short Port; char RecvBuffer[16]; - if( TcpM_SendWrapper(Sock, "\x05\x01\x00", 3) != 3 ) - { - ERRORMSG("Cannot communicate with TCP proxy, negotiation error.\n"); - return -1; - } + if( TcpM_SendWrapper(Sock, "\x05\x01\x00", 3) != 3 ) + { + ERRORMSG("Cannot communicate with TCP proxy, negotiation error.\n"); + return -1; + } if( TcpM_RecvWrapper(Sock, RecvBuffer, 2) != 2 ) { - ERRORMSG("Cannot communicate with TCP proxy, negotiation error.\n"); + ERRORMSG("Cannot communicate with TCP proxy, negotiation error.\n"); return -2; } - if( RecvBuffer[0] != '\x05' || RecvBuffer[1] != '\x00' ) - { - /*printf("---------3 : %x %x\n", RecvBuffer[0], RecvBuffer[1]);*/ - ERRORMSG("Cannot communicate with TCP proxy, negotiation error.\n"); - return -3; - } + if( RecvBuffer[0] != '\x05' || RecvBuffer[1] != '\x00' ) + { + /*printf("---------3 : %x %x\n", RecvBuffer[0], RecvBuffer[1]);*/ + ERRORMSG("Cannot communicate with TCP proxy, negotiation error.\n"); + return -3; + } - memcpy(AddressInfos, "\x05\x01\x00\x03", 4); + memcpy(AddressInfos, "\x05\x01\x00\x03", 4); if( Family == AF_INET ) { IPv4AddressToAsc(&(((const struct sockaddr_in *)NestedAddress)->sin_addr), AddressString); - Port = ((const struct sockaddr_in *)NestedAddress)->sin_port; + Port = ((const struct sockaddr_in *)NestedAddress)->sin_port; } else { - IPv6AddressToAsc(&(((const struct sockaddr_in6 *)NestedAddress)->sin6_addr), AddressString); - Port = ((const struct sockaddr_in6 *)NestedAddress)->sin6_port; + IPv6AddressToAsc(&(((const struct sockaddr_in6 *)NestedAddress)->sin6_addr), AddressString); + Port = ((const struct sockaddr_in6 *)NestedAddress)->sin6_port; } NumberOfCharacter = strlen(AddressString); @@ -204,78 +204,78 @@ static int TcpM_ProxyPreparation(SOCKET Sock, sizeof(Port) ); - INFO("Connecting to TCP server.\n"); + INFO("Connecting to TCP server.\n"); - if( TcpM_SendWrapper(Sock, + if( TcpM_SendWrapper(Sock, AddressInfos, 4 + 1 + NumberOfCharacter + 2 ) != 4 + 1 + NumberOfCharacter + 2 ) - { - ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); - return -4; - } + { + ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); + return -4; + } /* - if( TcpM_SendWrapper(Sock, "\x05\x01\x00\x03", 4) != 4 ) - { - ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); - return -4; - } - - if( TcpM_SendWrapper(Sock, &NumberOfCharacter, 1) != 1 ) - { - ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); - return -5; - } - if( TcpM_SendWrapper(Sock, AddressString, NumberOfCharacter) != NumberOfCharacter ) - { - ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); - return -6; - } - if( TcpM_SendWrapper(Sock, (const char *)&Port, sizeof(Port)) != sizeof(Port) ) - { - ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); - return -7; - } + if( TcpM_SendWrapper(Sock, "\x05\x01\x00\x03", 4) != 4 ) + { + ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); + return -4; + } + + if( TcpM_SendWrapper(Sock, &NumberOfCharacter, 1) != 1 ) + { + ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); + return -5; + } + if( TcpM_SendWrapper(Sock, AddressString, NumberOfCharacter) != NumberOfCharacter ) + { + ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); + return -6; + } + if( TcpM_SendWrapper(Sock, (const char *)&Port, sizeof(Port)) != sizeof(Port) ) + { + ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); + return -7; + } */ if( TcpM_RecvWrapper(Sock, RecvBuffer, 4) != 4 ) { - ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); - return -9; + ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); + return -9; } - if( RecvBuffer[1] != '\x00' ) - { - ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); - return -10; - } - - switch( RecvBuffer[3] ) - { - case 0x01: - NumberOfCharacter = 6; - break; - - case 0x03: - TcpM_RecvWrapper(Sock, &NumberOfCharacter, 1); - NumberOfCharacter += 2; - break; - - case 0x04: - NumberOfCharacter = 18; - break; - - default: - /*printf("------Here : %d %d %d %d\n", RecvBuffer[0], RecvBuffer[1], RecvBuffer[2], RecvBuffer[3]);*/ - ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); - return -11; - } - ClearTCPSocketBuffer(Sock, NumberOfCharacter); - - INFO("Connected to TCP server.\n"); - - return 0; + if( RecvBuffer[1] != '\x00' ) + { + ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); + return -10; + } + + switch( RecvBuffer[3] ) + { + case 0x01: + NumberOfCharacter = 6; + break; + + case 0x03: + TcpM_RecvWrapper(Sock, &NumberOfCharacter, 1); + NumberOfCharacter += 2; + break; + + case 0x04: + NumberOfCharacter = 18; + break; + + default: + /*printf("------Here : %d %d %d %d\n", RecvBuffer[0], RecvBuffer[1], RecvBuffer[2], RecvBuffer[3]);*/ + ERRORMSG("Cannot communicate with TCP proxy, connection to TCP server error.\n"); + return -11; + } + ClearTCPSocketBuffer(Sock, NumberOfCharacter); + + INFO("Connected to TCP server.\n"); + + return 0; } diff --git a/udpm.c b/udpm.c index e2ef2e0f..c35868ae 100755 --- a/udpm.c +++ b/udpm.c @@ -53,7 +53,7 @@ static int UdpM_Cleanup(UdpM *m) static void UdpM_Works(UdpM *m) { - static const struct timeval ShortTime = {10, 0}; + static const struct timeval ShortTime = {10, 0}; struct timeval Timeout; struct sockaddr *addr; @@ -65,7 +65,7 @@ static void UdpM_Works(UdpM *m) #define LEFT_LENGTH (BUF_LENGTH - sizeof(IHeader)) char *Entity; - fd_set ReadSet, ReadySet; + fd_set ReadSet, ReadySet; ReceiveBuffer = SafeMalloc(BUF_LENGTH); if( ReceiveBuffer == NULL ) @@ -88,7 +88,7 @@ static void UdpM_Works(UdpM *m) EFFECTIVE_LOCK_GET(m->Lock); if( m->Parallels.addrs == NULL ) { - sa_family_t family; + sa_family_t family; addr = AddressList_GetOne(&(m->AddrList), &family); if( addr == NULL ) @@ -284,7 +284,7 @@ static int UdpM_Send(UdpM *m, } else { struct sockaddr *a; - sa_family_t family; + sa_family_t family; int State; @@ -316,7 +316,7 @@ static int UdpM_Send(UdpM *m, int UdpM_Init(UdpM *m, const char *Services, BOOL Parallel) { - StringList Addresses; + StringList Addresses; StringListIterator sli; const char *Itr; diff --git a/utils.c b/utils.c index b75be976..8a57df88 100755 --- a/utils.c +++ b/utils.c @@ -5,7 +5,7 @@ #ifdef WIN32 int Execute(const char *Cmd) { - int ret; + int ret; ret = system(Cmd); @@ -15,19 +15,19 @@ int Execute(const char *Cmd) #include int Execute(const char *Cmd) { - int ret; + int ret; - ret = system(Cmd); + ret = system(Cmd); - if( ret != -1 && WIFEXITED(ret) ) - { - if( WEXITSTATUS(ret) == 0 ) - { - return 0; - } - } + if( ret != -1 && WIFEXITED(ret) ) + { + if( WEXITSTATUS(ret) == 0 ) + { + return 0; + } + } - return -1; + return -1; } #endif /* WIN32 */ @@ -42,89 +42,89 @@ int Execute(const char *Cmd) #include "addresslist.h" #ifdef WIN32 - #ifdef MASKED - #include - #ifndef CryptStringToBinary - BOOL WINAPI CryptStringToBinaryA(const BYTE *,DWORD,DWORD,LPTSTR,DWORD *,DWORD *,DWORD *); - #define CryptStringToBinary CryptStringToBinaryA - #endif /* CryptStringToBinary */ - #endif /* MASKED */ + #ifdef MASKED + #include + #ifndef CryptStringToBinary + BOOL WINAPI CryptStringToBinaryA(const BYTE *,DWORD,DWORD,LPTSTR,DWORD *,DWORD *,DWORD *); + #define CryptStringToBinary CryptStringToBinaryA + #endif /* CryptStringToBinary */ + #endif /* MASKED */ #else /* WIN32 */ - #ifdef MASKED - #ifdef BASE64_DECODER_OPENSSL - #include - #include - #endif /* BASE64_DECODER_OPENSSL */ - #ifdef BASE64_DECODER_UUDECODE - #endif /* BASE64_DECODER_UUDECODE */ - #ifdef BASE64_DECODER_COREUTILS - #endif /* BASE64_DECODER_COREUTILS */ - #endif /* MASKED */ - - #ifdef HAVE_WORDEXP - #include - #endif + #ifdef MASKED + #ifdef BASE64_DECODER_OPENSSL + #include + #include + #endif /* BASE64_DECODER_OPENSSL */ + #ifdef BASE64_DECODER_UUDECODE + #endif /* BASE64_DECODER_UUDECODE */ + #ifdef BASE64_DECODER_COREUTILS + #endif /* BASE64_DECODER_COREUTILS */ + #endif /* MASKED */ + + #ifdef HAVE_WORDEXP + #include + #endif #endif /* WIN32 */ int SafeRealloc(void **Memory_ptr, size_t NewBytes) { - void *New; + void *New; - New = realloc(*Memory_ptr, NewBytes); + New = realloc(*Memory_ptr, NewBytes); - if(New != NULL) - { - *Memory_ptr = New; - return 0; - } else { - return -1; - } + if(New != NULL) + { + *Memory_ptr = New; + return 0; + } else { + return -1; + } } char *StrToLower(char *str) { - while( *str != '\0' ) - { - *str = tolower(*str); - ++str; - } - return str; + while( *str != '\0' ) + { + *str = tolower(*str); + ++str; + } + return str; } char *BoolToYesNo(BOOL value) { - return value == FALSE ? "No" : "Yes"; + return value == FALSE ? "No" : "Yes"; } int GetModulePath(char *Buffer, int BufferLength) { #ifdef WIN32 - int ModuleNameLength = 0; - char ModuleName[320]; - char *SlashPosition; + int ModuleNameLength = 0; + char ModuleName[320]; + char *SlashPosition; - if( BufferLength < 0 ) - return 0; + if( BufferLength < 0 ) + return 0; - ModuleNameLength = GetModuleFileName(NULL, ModuleName, sizeof(ModuleName) - 1); + ModuleNameLength = GetModuleFileName(NULL, ModuleName, sizeof(ModuleName) - 1); - if( ModuleNameLength == 0 ) - return 0; + if( ModuleNameLength == 0 ) + return 0; - SlashPosition = strrchr(ModuleName, '\\'); + SlashPosition = strrchr(ModuleName, '\\'); - if( SlashPosition == NULL ) - return 0; + if( SlashPosition == NULL ) + return 0; - *SlashPosition = '\0'; + *SlashPosition = '\0'; - strncpy(Buffer, ModuleName, BufferLength - 1); - Buffer[BufferLength - 1] = '\0'; + strncpy(Buffer, ModuleName, BufferLength - 1); + Buffer[BufferLength - 1] = '\0'; - return strlen(Buffer); + return strlen(Buffer); #else #warning Implement this #endif @@ -133,582 +133,582 @@ int GetModulePath(char *Buffer, int BufferLength) int GetErrorMsg(int Code, char *Buffer, int BufferLength) { - if( BufferLength < 0 || Buffer == NULL ) - { - return 0; - } + if( BufferLength < 0 || Buffer == NULL ) + { + return 0; + } #ifdef WIN32 - return FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - Code, - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - Buffer, - BufferLength, - NULL); + return FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + Code, + MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), + Buffer, + BufferLength, + NULL); #else - strncpy(Buffer, strerror(Code), BufferLength - 1); - Buffer[BufferLength - 1] ='\0'; - return strlen(Buffer); + strncpy(Buffer, strerror(Code), BufferLength - 1); + Buffer[BufferLength - 1] ='\0'; + return strlen(Buffer); #endif } char *GetCurDateAndTime(char *Buffer, int BufferLength) { - time_t rawtime; - struct tm *timeinfo; + time_t rawtime; + struct tm *timeinfo; - *Buffer = '\0'; - *(Buffer + BufferLength - 1) = '\0'; + *Buffer = '\0'; + *(Buffer + BufferLength - 1) = '\0'; - time(&rawtime); + time(&rawtime); - timeinfo = localtime(&rawtime); + timeinfo = localtime(&rawtime); - strftime(Buffer, BufferLength - 1 ,"%b %d %X", timeinfo); + strftime(Buffer, BufferLength - 1 ,"%b %d %X", timeinfo); - return Buffer; + return Buffer; } #ifdef MASKED -int Base64Decode(const char *File) +int Base64Decode(const char *File) { #ifdef WIN32 - FILE *fp = fopen(File, "rb"); - long FileSize; - DWORD OutFileSize = 0; - char *FileContent; - char *ResultContent; - - if( fp == NULL ) - { - return -1; - } - - if( fseek(fp, 0L, SEEK_END) != 0 ) - { - fclose(fp); - return -2; - } - - FileSize = ftell(fp); - - if( FileSize < 0 ) - { - fclose(fp); - return -3; - } - - if( fseek(fp, 0L, SEEK_SET) != 0 ) - { - fclose(fp); - return -4; - } - - FileContent = SafeMalloc(FileSize); - if( FileContent == NULL ) - { - fclose(fp); - return -5; - } - - if( fread(FileContent, 1, FileSize, fp) != FileSize ) - { - SafeFree(FileContent); - fclose(fp); - return -6; - } - - fclose(fp); - - fp = fopen(File, "wb"); - if( fp == NULL ) - { - SafeFree(FileContent); - return -7; - } - - if( CryptStringToBinary((LPCSTR)FileContent, FileSize, 0x00000001, NULL, &OutFileSize, NULL, NULL) != TRUE ) - { - SafeFree(FileContent); - fclose(fp); - return -8; - } - - ResultContent = SafeMalloc(OutFileSize); - if( ResultContent == NULL ) - { - SafeFree(FileContent); - fclose(fp); - return -9; - } - - - if( CryptStringToBinary((LPCSTR)FileContent, FileSize, 0x00000001, (BYTE *)ResultContent, &OutFileSize, NULL, NULL) != TRUE ) - { - SafeFree(ResultContent); - SafeFree(FileContent); - fclose(fp); - return -9; - } - - fwrite(ResultContent, 1, OutFileSize, fp); - - SafeFree(ResultContent); - SafeFree(FileContent); - fclose(fp); - return 0; + FILE *fp = fopen(File, "rb"); + long FileSize; + DWORD OutFileSize = 0; + char *FileContent; + char *ResultContent; + + if( fp == NULL ) + { + return -1; + } + + if( fseek(fp, 0L, SEEK_END) != 0 ) + { + fclose(fp); + return -2; + } + + FileSize = ftell(fp); + + if( FileSize < 0 ) + { + fclose(fp); + return -3; + } + + if( fseek(fp, 0L, SEEK_SET) != 0 ) + { + fclose(fp); + return -4; + } + + FileContent = SafeMalloc(FileSize); + if( FileContent == NULL ) + { + fclose(fp); + return -5; + } + + if( fread(FileContent, 1, FileSize, fp) != FileSize ) + { + SafeFree(FileContent); + fclose(fp); + return -6; + } + + fclose(fp); + + fp = fopen(File, "wb"); + if( fp == NULL ) + { + SafeFree(FileContent); + return -7; + } + + if( CryptStringToBinary((LPCSTR)FileContent, FileSize, 0x00000001, NULL, &OutFileSize, NULL, NULL) != TRUE ) + { + SafeFree(FileContent); + fclose(fp); + return -8; + } + + ResultContent = SafeMalloc(OutFileSize); + if( ResultContent == NULL ) + { + SafeFree(FileContent); + fclose(fp); + return -9; + } + + + if( CryptStringToBinary((LPCSTR)FileContent, FileSize, 0x00000001, (BYTE *)ResultContent, &OutFileSize, NULL, NULL) != TRUE ) + { + SafeFree(ResultContent); + SafeFree(FileContent); + fclose(fp); + return -9; + } + + fwrite(ResultContent, 1, OutFileSize, fp); + + SafeFree(ResultContent); + SafeFree(FileContent); + fclose(fp); + return 0; #else /* WIN32 */ #ifdef BASE64_DECODER_OPENSSL - BIO *ub64, *bmem; - - FILE *fp = fopen(File, "rb"); - long FileSize; - int OutputSize = 0; - char *FileContent; - char *ResultContent; - - if( fp == NULL ) - { - return -1; - } - - if( fseek(fp, 0L, SEEK_END) != 0 ) - { - fclose(fp); - return -2; - } - - FileSize = ftell(fp); - - if( FileSize < 0 ) - { - fclose(fp); - return -3; - } - - if( fseek(fp, 0L, SEEK_SET) != 0 ) - { - fclose(fp); - return -4; - } - - FileContent = SafeMalloc(FileSize); - if( FileContent == NULL ) - { - fclose(fp); - return -5; - } - - if( fread(FileContent, 1, FileSize, fp) != FileSize ) - { - SafeFree(FileContent); - fclose(fp); - return -6; - } - - fclose(fp); - - ub64 = BIO_new(BIO_f_base64()); - if( ub64 == NULL ) - { - SafeFree(FileContent); - return -7; - } - - bmem = BIO_new_mem_buf(FileContent, FileSize); - if( ub64 == NULL ) - { - SafeFree(FileContent); - return -8; - } - - fp = fopen(File, "wb"); - if( fp == NULL ) - { - BIO_free_all(bmem); - SafeFree(FileContent); - return -9; - } - - bmem = BIO_push(ub64, bmem); - if( bmem== NULL ) - { - SafeFree(FileContent); - fclose(fp); - return -10; - } - - ResultContent = SafeMalloc(FileSize); - if( ResultContent == NULL ) - { - BIO_free_all(bmem); - SafeFree(FileContent); - fclose(fp); - return -11; - } - - OutputSize = BIO_read(bmem, ResultContent, FileSize); - if( OutputSize < 1 ) - { - BIO_free_all(bmem); - SafeFree(ResultContent); - SafeFree(FileContent); - fclose(fp); - return -12; - } - - fwrite(ResultContent, 1, OutputSize, fp); - - BIO_free_all(bmem); - SafeFree(ResultContent); - SafeFree(FileContent); - fclose(fp); - return 0; + BIO *ub64, *bmem; + + FILE *fp = fopen(File, "rb"); + long FileSize; + int OutputSize = 0; + char *FileContent; + char *ResultContent; + + if( fp == NULL ) + { + return -1; + } + + if( fseek(fp, 0L, SEEK_END) != 0 ) + { + fclose(fp); + return -2; + } + + FileSize = ftell(fp); + + if( FileSize < 0 ) + { + fclose(fp); + return -3; + } + + if( fseek(fp, 0L, SEEK_SET) != 0 ) + { + fclose(fp); + return -4; + } + + FileContent = SafeMalloc(FileSize); + if( FileContent == NULL ) + { + fclose(fp); + return -5; + } + + if( fread(FileContent, 1, FileSize, fp) != FileSize ) + { + SafeFree(FileContent); + fclose(fp); + return -6; + } + + fclose(fp); + + ub64 = BIO_new(BIO_f_base64()); + if( ub64 == NULL ) + { + SafeFree(FileContent); + return -7; + } + + bmem = BIO_new_mem_buf(FileContent, FileSize); + if( ub64 == NULL ) + { + SafeFree(FileContent); + return -8; + } + + fp = fopen(File, "wb"); + if( fp == NULL ) + { + BIO_free_all(bmem); + SafeFree(FileContent); + return -9; + } + + bmem = BIO_push(ub64, bmem); + if( bmem== NULL ) + { + SafeFree(FileContent); + fclose(fp); + return -10; + } + + ResultContent = SafeMalloc(FileSize); + if( ResultContent == NULL ) + { + BIO_free_all(bmem); + SafeFree(FileContent); + fclose(fp); + return -11; + } + + OutputSize = BIO_read(bmem, ResultContent, FileSize); + if( OutputSize < 1 ) + { + BIO_free_all(bmem); + SafeFree(ResultContent); + SafeFree(FileContent); + fclose(fp); + return -12; + } + + fwrite(ResultContent, 1, OutputSize, fp); + + BIO_free_all(bmem); + SafeFree(ResultContent); + SafeFree(FileContent); + fclose(fp); + return 0; #endif /* BASE64_DECODER_OPENSSL */ #ifdef BASE64_DECODER_UUDECODE - char Cmd[2048]; - FILE *fp; + char Cmd[2048]; + FILE *fp; - sprintf(Cmd, "%s.base64", File); + sprintf(Cmd, "%s.base64", File); - fp = fopen(Cmd, "w"); - if( fp == NULL ) - { - return -1; - } + fp = fopen(Cmd, "w"); + if( fp == NULL ) + { + return -1; + } - fputs("begin-base64 775 \xA7\x0A", fp); + fputs("begin-base64 775 \xA7\x0A", fp); - fclose(fp); + fclose(fp); - sprintf(Cmd, "cat %s >> %s.base64", File, File); + sprintf(Cmd, "cat %s >> %s.base64", File, File); - if( Execute(Cmd) != 0 ) - { - return -1; - } + if( Execute(Cmd) != 0 ) + { + return -1; + } - sprintf(Cmd, "rm %s", File); + sprintf(Cmd, "rm %s", File); - if( Execute(Cmd) != 0 ) - { - return -1; - } + if( Execute(Cmd) != 0 ) + { + return -1; + } - sprintf(Cmd, "uudecode -o %s %s.base64", File, File); + sprintf(Cmd, "uudecode -o %s %s.base64", File, File); - Execute(Cmd); + Execute(Cmd); - return 0; + return 0; #endif /* BASE64_DECODER_UUDECODE */ #ifdef BASE64_DECODER_COREUTILS - char Cmd[2048]; - FILE *fp; + char Cmd[2048]; + FILE *fp; - sprintf(Cmd, "%s.base64", File); + sprintf(Cmd, "%s.base64", File); - fp = fopen(Cmd, "w"); - if( fp == NULL ) - { - return -1; - } + fp = fopen(Cmd, "w"); + if( fp == NULL ) + { + return -1; + } - fclose(fp); + fclose(fp); - sprintf(Cmd, "cat %s >> %s.base64", File, File); + sprintf(Cmd, "cat %s >> %s.base64", File, File); - if( Execute(Cmd) != 0 ) - { - return -1; - } + if( Execute(Cmd) != 0 ) + { + return -1; + } - sprintf(Cmd, "rm %s", File); + sprintf(Cmd, "rm %s", File); - if( Execute(Cmd) != 0 ) - { - return -1; - } + if( Execute(Cmd) != 0 ) + { + return -1; + } - sprintf(Cmd, "base64 -d %s.base64 > %s", File, File); + sprintf(Cmd, "base64 -d %s.base64 > %s", File, File); - Execute(Cmd); + Execute(Cmd); - return 0; + return 0; #endif /* BASE64_DECODER_COREUTILS */ #endif /* WIN32 */ } #endif /* MASKED */ int IPv6AddressToNum(const char *asc, void *Buffer) { - int16_t *buf_s = (int16_t *)Buffer; - const char *itr; - - memset(Buffer, 0, 16); - - for(; isspace(*asc); ++asc); - - if( strstr(asc, "::") == NULL ) - { /* full format */ - int a[8]; - sscanf(asc, "%x:%x:%x:%x:%x:%x:%x:%x", - a, a + 1, a + 2, a + 3, a + 4, a + 5, a + 6, a + 7 - ); - SET_16_BIT_U_INT(buf_s, a[0]); - SET_16_BIT_U_INT(buf_s + 1, a[1]); - SET_16_BIT_U_INT(buf_s + 2, a[2]); - SET_16_BIT_U_INT(buf_s + 3, a[3]); - SET_16_BIT_U_INT(buf_s + 4, a[4]); - SET_16_BIT_U_INT(buf_s + 5, a[5]); - SET_16_BIT_U_INT(buf_s + 6, a[6]); - SET_16_BIT_U_INT(buf_s + 7, a[7]); - } else { - /* not full*/ - - if( asc[2] == '\0' || isspace(asc[2]) ) - { - memset(Buffer, 0, 16); - return 0; - } - - while(1) - { - int a; - itr = asc; - asc = strchr(asc, ':'); - if( asc == NULL ) - return 0; - - if( itr == asc ) - { - break; - } - - sscanf(itr, "%x:", &a); - SET_16_BIT_U_INT(buf_s, a); - ++buf_s; - ++asc; - } - buf_s = (int16_t *)Buffer + 7; - for(; *asc != '\0'; ++asc); - while(1) - { - int a; - for(itr = asc; *itr != ':'; --itr); - - if( *(itr + 1) == '\0' ) - break; - - sscanf(itr + 1, "%x", &a); - SET_16_BIT_U_INT(buf_s, a); - --buf_s; - asc = itr - 1; - - if( *(itr - 1) == ':' ) - break; - } - } - return 0; + int16_t *buf_s = (int16_t *)Buffer; + const char *itr; + + memset(Buffer, 0, 16); + + for(; isspace(*asc); ++asc); + + if( strstr(asc, "::") == NULL ) + { /* full format */ + int a[8]; + sscanf(asc, "%x:%x:%x:%x:%x:%x:%x:%x", + a, a + 1, a + 2, a + 3, a + 4, a + 5, a + 6, a + 7 + ); + SET_16_BIT_U_INT(buf_s, a[0]); + SET_16_BIT_U_INT(buf_s + 1, a[1]); + SET_16_BIT_U_INT(buf_s + 2, a[2]); + SET_16_BIT_U_INT(buf_s + 3, a[3]); + SET_16_BIT_U_INT(buf_s + 4, a[4]); + SET_16_BIT_U_INT(buf_s + 5, a[5]); + SET_16_BIT_U_INT(buf_s + 6, a[6]); + SET_16_BIT_U_INT(buf_s + 7, a[7]); + } else { + /* not full*/ + + if( asc[2] == '\0' || isspace(asc[2]) ) + { + memset(Buffer, 0, 16); + return 0; + } + + while(1) + { + int a; + itr = asc; + asc = strchr(asc, ':'); + if( asc == NULL ) + return 0; + + if( itr == asc ) + { + break; + } + + sscanf(itr, "%x:", &a); + SET_16_BIT_U_INT(buf_s, a); + ++buf_s; + ++asc; + } + buf_s = (int16_t *)Buffer + 7; + for(; *asc != '\0'; ++asc); + while(1) + { + int a; + for(itr = asc; *itr != ':'; --itr); + + if( *(itr + 1) == '\0' ) + break; + + sscanf(itr + 1, "%x", &a); + SET_16_BIT_U_INT(buf_s, a); + --buf_s; + asc = itr - 1; + + if( *(itr - 1) == ':' ) + break; + } + } + return 0; } int IPv4AddressToNum(const char *asc, void *Buffer) { - int ret = 0; + int ret = 0; - unsigned char *BufferInByte = (unsigned char *)Buffer; + unsigned char *BufferInByte = (unsigned char *)Buffer; - int Components[4]; + int Components[4]; - ret = sscanf(asc, "%d.%d.%d.%d", Components, Components + 1, Components + 2, Components + 3); - BufferInByte[0] = Components[0]; - BufferInByte[1] = Components[1]; - BufferInByte[2] = Components[2]; - BufferInByte[3] = Components[3]; + ret = sscanf(asc, "%d.%d.%d.%d", Components, Components + 1, Components + 2, Components + 3); + BufferInByte[0] = Components[0]; + BufferInByte[1] = Components[1]; + BufferInByte[2] = Components[2]; + BufferInByte[3] = Components[3]; - return ret; + return ret; } sa_family_t GetAddressFamily(const char *Addr) { - char Buffer[8]; + char Buffer[8]; - if( strchr(Addr, '[') != NULL ) - { - return AF_INET6; - } + if( strchr(Addr, '[') != NULL ) + { + return AF_INET6; + } - if( IPv4AddressToNum(Addr, Buffer) == 4 ) - { - return AF_INET; - } + if( IPv4AddressToNum(Addr, Buffer) == 4 ) + { + return AF_INET; + } - return AF_UNSPEC; + return AF_UNSPEC; } int IPv6AddressToAsc(const void *Address, void *Buffer) { - sprintf((char *)Buffer, "%x:%x:%x:%x:%x:%x:%x:%x", - GET_16_BIT_U_INT((const char *)Address), - GET_16_BIT_U_INT((const char *)Address + 2), - GET_16_BIT_U_INT((const char *)Address + 4), - GET_16_BIT_U_INT((const char *)Address + 6), - GET_16_BIT_U_INT((const char *)Address + 8), - GET_16_BIT_U_INT((const char *)Address + 10), - GET_16_BIT_U_INT((const char *)Address + 12), - GET_16_BIT_U_INT((const char *)Address + 14) - - ); - - return 0; + sprintf((char *)Buffer, "%x:%x:%x:%x:%x:%x:%x:%x", + GET_16_BIT_U_INT((const char *)Address), + GET_16_BIT_U_INT((const char *)Address + 2), + GET_16_BIT_U_INT((const char *)Address + 4), + GET_16_BIT_U_INT((const char *)Address + 6), + GET_16_BIT_U_INT((const char *)Address + 8), + GET_16_BIT_U_INT((const char *)Address + 10), + GET_16_BIT_U_INT((const char *)Address + 12), + GET_16_BIT_U_INT((const char *)Address + 14) + + ); + + return 0; } int IPv4AddressToAsc(const void *Address, void *Buffer) { const char *a = (const char *)Address; - sprintf(Buffer, "%u.%u.%u.%u", GET_8_BIT_U_INT(a), + sprintf(Buffer, "%u.%u.%u.%u", GET_8_BIT_U_INT(a), GET_8_BIT_U_INT(a + 1), GET_8_BIT_U_INT(a + 2), GET_8_BIT_U_INT(a + 3) ); - return 0; + return 0; } -int GetConfigDirectory(char *out) +int GetConfigDirectory(char *out) { #ifdef WIN32 - return -1; + return -1; #else /* WIN32 */ #ifndef ANDROID - struct passwd *pw = getpwuid(getuid()); - char *home = pw->pw_dir; - *out = '\0'; - if( home == NULL ) - return 1; + struct passwd *pw = getpwuid(getuid()); + char *home = pw->pw_dir; + *out = '\0'; + if( home == NULL ) + return 1; - strcpy(out, home); - strcat(out, "/.dnsforwarder"); + strcpy(out, home); + strcat(out, "/.dnsforwarder"); - return 0; + return 0; #else /* ANDROID */ - strcpy(out, "/system/root/.dnsforwarder"); + strcpy(out, "/system/root/.dnsforwarder"); #endif /* ANDROID */ #endif /* WIN32 */ } BOOL FileIsReadable(const char *File) { - FILE *fp = fopen(File, "r"); - - if( fp == NULL ) - { - return FALSE; - } else { - fclose(fp); - return TRUE; - } + FILE *fp = fopen(File, "r"); + + if( fp == NULL ) + { + return FALSE; + } else { + fclose(fp); + return TRUE; + } } int GetFileSizePortable(const char *File) { - int s = 0; - FILE *fp = fopen(File, "rb"); + int s = 0; + FILE *fp = fopen(File, "rb"); - if( fp == NULL ) - { - return 0; - } + if( fp == NULL ) + { + return 0; + } - if( fseek(fp, 0, SEEK_END) == 0 ) - { - s = ftell(fp); - } + if( fseek(fp, 0, SEEK_END) == 0 ) + { + s = ftell(fp); + } - fclose(fp); - return s; + fclose(fp); + return s; } int GetTextFileContent(const char *File, char *Content) { - FILE *fp = fopen(File, "rb"); - int c = 0; + FILE *fp = fopen(File, "rb"); + int c = 0; - if( fp == NULL ) - { - return -1; - } + if( fp == NULL ) + { + return -1; + } - while( (c = fgetc(fp)) != EOF ) - { - *Content++ = c; - } + while( (c = fgetc(fp)) != EOF ) + { + *Content++ = c; + } - fclose(fp); + fclose(fp); - return 0; + return 0; } BOOL IsPrime(int n) { - int i; - - if( n < 2 ) - { - return FALSE; - } - - if( n == 2 ) - { - return TRUE; - } - - if( n % 2 == 0 ) - { - return FALSE; - } - - for(i = 3; i < sqrt(n) + 1; i += 2) - { - if( n % i == 0 ) - { - return FALSE; - } - } - - return TRUE; + int i; + + if( n < 2 ) + { + return FALSE; + } + + if( n == 2 ) + { + return TRUE; + } + + if( n % 2 == 0 ) + { + return FALSE; + } + + for(i = 3; i < sqrt(n) + 1; i += 2) + { + if( n % i == 0 ) + { + return FALSE; + } + } + + return TRUE; } int FindNextPrime(int Current) { - if( IsPrime(Current) ) - { - return Current; - } - - Current = ROUND_UP(Current, 2) + 1; - - do - { - if( IsPrime(Current) ) - { - return Current; - } else { - Current += 2; - } - - } while( TRUE ); + if( IsPrime(Current) ) + { + return Current; + } + + Current = ROUND_UP(Current, 2) + 1; + + do + { + if( IsPrime(Current) ) + { + return Current; + } else { + Current += 2; + } + + } while( TRUE ); } BOOL ContainWildCard(const char *item) { - if( strchr(item, '?') != NULL || strchr(item, '*') != NULL ) - { - return TRUE; - } else { - return FALSE; - } + if( strchr(item, '?') != NULL || strchr(item, '*') != NULL ) + { + return TRUE; + } else { + return FALSE; + } } unsigned int BKDRHash(const char* str, unsigned int Unused) @@ -727,145 +727,145 @@ unsigned int BKDRHash(const char* str, unsigned int Unused) void HexDump(const char *Data, int Length) { - int Itr; + int Itr; - for( Itr = 0; Itr != Length; ++Itr ) - { - printf("%x ", (unsigned char)Data[Itr]); - } + for( Itr = 0; Itr != Length; ++Itr ) + { + printf("%x ", (unsigned char)Data[Itr]); + } - putchar('\n'); + putchar('\n'); } char *BinaryOutput(const char *Origin, int OriginLength, char *Buffer) { - int loop; - - while( OriginLength != 0 ) - { - for( loop = 7; loop <= 0; --loop ) - { - if( (((int)*Origin) & (1 << loop)) == 0 ) - { - *Buffer = '0'; - } else { - *Buffer = '1'; - } - - ++Buffer; - } - - --OriginLength; - ++Origin; - } - - *Buffer = '\0'; - return Buffer + 1; + int loop; + + while( OriginLength != 0 ) + { + for( loop = 7; loop <= 0; --loop ) + { + if( (((int)*Origin) & (1 << loop)) == 0 ) + { + *Buffer = '0'; + } else { + *Buffer = '1'; + } + + ++Buffer; + } + + --OriginLength; + ++Origin; + } + + *Buffer = '\0'; + return Buffer + 1; } char *StringDup(const char *Str) { - char *New; + char *New; - if( Str == NULL ) - { - return NULL; - } + if( Str == NULL ) + { + return NULL; + } - New = malloc(strlen(Str) + 1); - if( New != NULL ) - { - strcpy(New, Str); - } + New = malloc(strlen(Str) + 1); + if( New != NULL ) + { + strcpy(New, Str); + } - return New; + return New; } char *StrNpbrk(char *Str, const char *Ch) { - if( Str == NULL || Ch == NULL ) - { - return Str; - } - - while( *Str != '\0' && strchr(Ch, *Str) != NULL ) - { - ++Str; - } - - if( *Str == '\0' ) - { - return NULL; - } else { - return Str; - } + if( Str == NULL || Ch == NULL ) + { + return Str; + } + + while( *Str != '\0' && strchr(Ch, *Str) != NULL ) + { + ++Str; + } + + if( *Str == '\0' ) + { + return NULL; + } else { + return Str; + } } char *StrRNpbrk(char *Str, const char *Ch) { - char *LastCharacter; + char *LastCharacter; - if( Str == NULL || Ch == NULL ) - { - return Str; - } + if( Str == NULL || Ch == NULL ) + { + return Str; + } - LastCharacter = Str + strlen(Str) - 1; + LastCharacter = Str + strlen(Str) - 1; - while( LastCharacter >= Str && strchr(Ch, *LastCharacter) != NULL ) - { - --LastCharacter; - } + while( LastCharacter >= Str && strchr(Ch, *LastCharacter) != NULL ) + { + --LastCharacter; + } - if( LastCharacter < Str ) - { - return NULL; - } else { - return LastCharacter; - } + if( LastCharacter < Str ) + { + return NULL; + } else { + return LastCharacter; + } } char *GoToNextNonSpace(const char *Here) { - return (char *)StrNpbrk((char *)Here, "\t "); + return (char *)StrNpbrk((char *)Here, "\t "); } char *GoToPrevNonSpace(char *Here) { - for( ; isspace(*Here); --Here ); + for( ; isspace(*Here); --Here ); - return Here; + return Here; } int GetAddressLength(sa_family_t Family) { - switch( Family ) - { - case AF_INET: - return sizeof(struct sockaddr); - break; - - case AF_INET6: - return sizeof(struct sockaddr_in6); - break; - - default: - return -1; - break; - } + switch( Family ) + { + case AF_INET: + return sizeof(struct sockaddr); + break; + + case AF_INET6: + return sizeof(struct sockaddr_in6); + break; + + default: + return -1; + break; + } } int SetProgramEnvironment(const char *Name, const char *Value) { #ifdef WIN32 - return !SetEnvironmentVariable(Name, Value); + return !SetEnvironmentVariable(Name, Value); #else #ifdef HAVE_SETENV - return setenv(Name, Value, 1); + return setenv(Name, Value, 1); #else - return 0; + return 0; #endif #endif } @@ -873,145 +873,145 @@ int SetProgramEnvironment(const char *Name, const char *Value) int ExpandPath(char *String, int BufferLength) { #ifdef WIN32 - char TempStr[2048]; - int State; + char TempStr[2048]; + int State; - State = ExpandEnvironmentStrings(String, TempStr, sizeof(TempStr) - 1); + State = ExpandEnvironmentStrings(String, TempStr, sizeof(TempStr) - 1); - if( State == 0 || State >= sizeof(TempStr) - 1 ) - { - return -1; - } + if( State == 0 || State >= sizeof(TempStr) - 1 ) + { + return -1; + } - TempStr[sizeof(TempStr) - 1] = '\0'; + TempStr[sizeof(TempStr) - 1] = '\0'; - if( strlen(TempStr) + 1 > BufferLength ) - { - return -1; - } + if( strlen(TempStr) + 1 > BufferLength ) + { + return -1; + } - strcpy(String, TempStr); + strcpy(String, TempStr); - return 0; + return 0; #else #ifdef HAVE_WORDEXP - wordexp_t Result; + wordexp_t Result; - if( wordexp(String, &Result, 0) != 0 ) - { - wordfree(&Result); - return -1; - } + if( wordexp(String, &Result, 0) != 0 ) + { + wordfree(&Result); + return -1; + } - if( strlen(Result.we_wordv[0]) + 1 <= BufferLength ) - { - strcpy(String, Result.we_wordv[0]); - } + if( strlen(Result.we_wordv[0]) + 1 <= BufferLength ) + { + strcpy(String, Result.we_wordv[0]); + } - wordfree(&Result); - return 0; + wordfree(&Result); + return 0; #else - return 0; + return 0; #endif #endif } char *GetLocalPathFromURL(const char *URL, char *Buffer, int BufferLength) { - const char *Itr; + const char *Itr; #ifdef WIN32 - char *Itr_Buffer; + char *Itr_Buffer; #endif - Itr = strstr(URL, "://"); - if( Itr == NULL ) - { - return NULL; - } + Itr = strstr(URL, "://"); + if( Itr == NULL ) + { + return NULL; + } - ++Itr; - for( ; *Itr == '/'; ++Itr ); + ++Itr; + for( ; *Itr == '/'; ++Itr ); #ifndef WIN32 - --Itr; + --Itr; #endif - if( strlen(Itr) + 1 > BufferLength ) - { - return NULL; - } + if( strlen(Itr) + 1 > BufferLength ) + { + return NULL; + } - strcpy(Buffer, Itr); + strcpy(Buffer, Itr); #ifdef WIN32 - for( Itr_Buffer = Buffer; *Itr_Buffer != '\0'; ++Itr_Buffer ) - { - if( *Itr_Buffer == '/' ) - { - *Itr_Buffer = '\\'; - } - } + for( Itr_Buffer = Buffer; *Itr_Buffer != '\0'; ++Itr_Buffer ) + { + if( *Itr_Buffer == '/' ) + { + *Itr_Buffer = '\\'; + } + } #endif - if( ExpandPath(Buffer, BufferLength) == 0 ) - { - return Buffer; - } else { - return NULL; - } + if( ExpandPath(Buffer, BufferLength) == 0 ) + { + return Buffer; + } else { + return NULL; + } } int CopyAFile(const char *Src, const char *Dst, BOOL Append) { - FILE *Src_Fp, *Dst_Fp; - int ch; - - Src_Fp = fopen(Src, "r"); - if( Src_Fp == NULL ) - { - return -1; - } - - Dst_Fp = fopen(Dst, Append == TRUE ? "a+" : "w"); - if( Dst_Fp == NULL ) - { - fclose(Src_Fp); - return -2; - } - - do{ - ch = fgetc(Src_Fp); - if( ch != EOF && !feof(Src_Fp) ) - { - fputc(ch, Dst_Fp); - } else { - break; - } - - } while( TRUE ); - - fclose(Src_Fp); - fclose(Dst_Fp); - - return 0; + FILE *Src_Fp, *Dst_Fp; + int ch; + + Src_Fp = fopen(Src, "r"); + if( Src_Fp == NULL ) + { + return -1; + } + + Dst_Fp = fopen(Dst, Append == TRUE ? "a+" : "w"); + if( Dst_Fp == NULL ) + { + fclose(Src_Fp); + return -2; + } + + do{ + ch = fgetc(Src_Fp); + if( ch != EOF && !feof(Src_Fp) ) + { + fputc(ch, Dst_Fp); + } else { + break; + } + + } while( TRUE ); + + fclose(Src_Fp); + fclose(Dst_Fp); + + return 0; } int FatalErrorDecideding(int LastError) { #ifdef WIN32 - if( LastError == WSAEWOULDBLOCK || LastError == WSAEINVAL || LastError == WSAEINTR || LastError == WSAEINPROGRESS ) - { - return 0; - } + if( LastError == WSAEWOULDBLOCK || LastError == WSAEINVAL || LastError == WSAEINTR || LastError == WSAEINPROGRESS ) + { + return 0; + } #else - if( LastError == EINTR || LastError == EAGAIN || LastError == EINPROGRESS ) - { - return 0; - } + if( LastError == EINTR || LastError == EAGAIN || LastError == EINPROGRESS ) + { + return 0; + } #endif - return -1; + return -1; } int CountSubStr(const char *Src, const char *SubStr) @@ -1075,98 +1075,98 @@ char *ReplaceStr_WithLengthChecking(char *Src, int SetSocketNonBlock(SOCKET sock, BOOL NonBlocked) { #ifdef WIN32 - unsigned long NonBlock = 1; - - if( ioctlsocket(sock, FIONBIO, &NonBlock) != 0 ) - { - return -1; - } else { - return 0; - } + unsigned long NonBlock = 1; + + if( ioctlsocket(sock, FIONBIO, &NonBlock) != 0 ) + { + return -1; + } else { + return 0; + } #else - int Flags; - int BlockFlag; + int Flags; + int BlockFlag; - Flags = fcntl(sock, F_GETFL, 0); - if( Flags < 0 ) - { - return -1; - } + Flags = fcntl(sock, F_GETFL, 0); + if( Flags < 0 ) + { + return -1; + } - if( NonBlocked == TRUE ) - { + if( NonBlocked == TRUE ) + { BlockFlag = O_NONBLOCK; - } else { + } else { BlockFlag = ~O_NONBLOCK; - } + } - if( fcntl(sock, F_SETFL, Flags | BlockFlag) < 0 ) - { - return -1; - } + if( fcntl(sock, F_SETFL, Flags | BlockFlag) < 0 ) + { + return -1; + } - return 0; + return 0; #endif } BOOL SocketIsWritable(SOCKET sock, int Timeout) { - struct timeval TimeLimit = {Timeout / 1000, (Timeout % 1000) * 1000}; - fd_set rfd; - - if( sock == INVALID_SOCKET ) - { - return FALSE; - } - - FD_ZERO(&rfd); - FD_SET(sock, &rfd); - - switch(select(sock + 1, NULL, &rfd, NULL, &TimeLimit)) - { - case 0: - case SOCKET_ERROR: - return FALSE; - break; - - default: - return TRUE; - break; - } + struct timeval TimeLimit = {Timeout / 1000, (Timeout % 1000) * 1000}; + fd_set rfd; + + if( sock == INVALID_SOCKET ) + { + return FALSE; + } + + FD_ZERO(&rfd); + FD_SET(sock, &rfd); + + switch(select(sock + 1, NULL, &rfd, NULL, &TimeLimit)) + { + case 0: + case SOCKET_ERROR: + return FALSE; + break; + + default: + return TRUE; + break; + } } BOOL SocketIsStillReadable(SOCKET Sock, int timeout) { - fd_set rfd; - struct timeval TimeLimit = {timeout / 1000, (timeout % 1000) * 1000}; - - FD_ZERO(&rfd); - FD_SET(Sock, &rfd); - - switch(select(Sock + 1, &rfd, NULL, NULL, &TimeLimit)) - { - case SOCKET_ERROR: - case 0: - return FALSE; - break; - case 1: - return TRUE; - break; - default: - return FALSE; - break; - } + fd_set rfd; + struct timeval TimeLimit = {timeout / 1000, (timeout % 1000) * 1000}; + + FD_ZERO(&rfd); + FD_SET(Sock, &rfd); + + switch(select(Sock + 1, &rfd, NULL, NULL, &TimeLimit)) + { + case SOCKET_ERROR: + case 0: + return FALSE; + break; + case 1: + return TRUE; + break; + default: + return FALSE; + break; + } } void ClearTCPSocketBuffer(SOCKET Sock, int Length) { - char BlackHole[128]; + char BlackHole[128]; - while( Length > 0 ) - { - int UnitLength; + while( Length > 0 ) + { + int UnitLength; - UnitLength = recv(Sock, + UnitLength = recv(Sock, BlackHole, sizeof(BlackHole) < Length ? sizeof(BlackHole) : Length, 0 @@ -1177,24 +1177,24 @@ void ClearTCPSocketBuffer(SOCKET Sock, int Length) return; } - Length -= UnitLength; - } + Length -= UnitLength; + } } SOCKET TryBindLocal(BOOL Ipv6, int StartPort, Address_Type *Address) { const char *Loopback = Ipv6 ? "[::1]" : "127.0.0.1"; - int MaxTime = 10000; + int MaxTime = 10000; - Address_Type Address1; - SOCKET ret = INVALID_SOCKET; + Address_Type Address1; + SOCKET ret = INVALID_SOCKET; - do { - AddressList_ConvertFromString(&Address1, Loopback, StartPort); + do { + AddressList_ConvertFromString(&Address1, Loopback, StartPort); - ret = socket(Address1.family, SOCK_DGRAM, IPPROTO_UDP); - if( ret == INVALID_SOCKET ) + ret = socket(Address1.family, SOCK_DGRAM, IPPROTO_UDP); + if( ret == INVALID_SOCKET ) { continue; } @@ -1210,28 +1210,28 @@ SOCKET TryBindLocal(BOOL Ipv6, int StartPort, Address_Type *Address) continue; } - } while( ret == INVALID_SOCKET && --MaxTime > 0 && ++StartPort > 0 ); + } while( ret == INVALID_SOCKET && --MaxTime > 0 && ++StartPort > 0 ); - if( ret != INVALID_SOCKET && Address != NULL ) + if( ret != INVALID_SOCKET && Address != NULL ) { memcpy(Address, &Address1, sizeof(Address_Type)); } - return ret; + return ret; } char *SplitNameAndValue(char *Line, const char *Delimiters) { - char *Delimiter = strpbrk(Line, Delimiters); + char *Delimiter = strpbrk(Line, Delimiters); - if( Delimiter == NULL ) - { - return NULL; - } + if( Delimiter == NULL ) + { + return NULL; + } - *Delimiter = '\0'; + *Delimiter = '\0'; - return GoToNextNonSpace(Delimiter + 1); + return GoToNextNonSpace(Delimiter + 1); } char *GetPathPart(char *FullPath) diff --git a/utils.h b/utils.h index e376457d..91373fd5 100755 --- a/utils.h +++ b/utils.h @@ -6,9 +6,9 @@ #include "common.h" -#define ROUND_DOWN(val, base) ((val) / (base) * (base)) -#define ROUND(val, base) ROUND_DOWN((val) + (base) / 2, base) -#define ROUND_UP(val, base) ROUND_DOWN((val) + (base) - 1, base) +#define ROUND_DOWN(val, base) ((val) / (base) * (base)) +#define ROUND(val, base) ROUND_DOWN((val) + (base) / 2, base) +#define ROUND_UP(val, base) ROUND_DOWN((val) + (base) - 1, base) #define STRINGIZING(val) # val #define STRINGIZINGINT(val) STRINGIZING(val) @@ -19,7 +19,7 @@ typedef int offset_t; typedef int (*CompareFunc)(const void *, const void *); -#define CURRENT_THREAD_ID (GET_THREAD_ID()) +#define CURRENT_THREAD_ID (GET_THREAD_ID()) /* void *SafeMalloc(size_t Bytes); * Description: @@ -29,7 +29,7 @@ typedef int (*CompareFunc)(const void *, const void *); * Return value: * The first address of the allocated block of memory. */ -#define SafeMalloc malloc +#define SafeMalloc malloc /* void SafeFree(void *Memory); * Description: @@ -37,7 +37,7 @@ typedef int (*CompareFunc)(const void *, const void *); * Parameters: * Memory:The first address of the memory to be freed. */ -#define SafeFree free +#define SafeFree free /* int SafeRealloc(void **Memory_ptr, size_t NewBytes); * Description: @@ -78,7 +78,7 @@ char *GetCurDateAndTime(char *Buffer, int BufferLength); int Execute(const char *Cmd); -int Base64Decode(const char *File); +int Base64Decode(const char *File); int IPv6AddressToNum(const char *asc, void *Buffer); @@ -90,7 +90,7 @@ int IPv6AddressToAsc(const void *Address, void *Buffer); int IPv4AddressToAsc(const void *Address, void *Buffer); -int GetConfigDirectory(char *out); +int GetConfigDirectory(char *out); BOOL FileIsReadable(const char *File);