コード例 #1
0
ファイル: IP2Country.cpp プロジェクト: 0vermind/hmule
const CountryData& CIP2Country::GetCountryData(const wxString &ip)
{
	// Should prevent the crash if the GeoIP database does not exists
	if (m_geoip == NULL) {
		CountryDataMap::iterator it = m_CountryDataMap.find(wxString(wxT("unknown")));
		it->second.Name = wxT("?");
		return it->second;	
	}
	
	const wxString CCode = wxString(char2unicode(GeoIP_country_code_by_addr(m_geoip, unicode2char(ip)))).MakeLower();
	
	CountryDataMap::iterator it = m_CountryDataMap.find(CCode);
	if (it == m_CountryDataMap.end()) { 
		// Show the code and ?? flag
		it = m_CountryDataMap.find(wxString(wxT("unknown")));
		wxASSERT(it != m_CountryDataMap.end());
		if (CCode.IsEmpty()) {
			it->second.Name = wxT("?");
		} else{
			it->second.Name = CCode;			
		}
	}
	
	return it->second;	
}
コード例 #2
0
ファイル: tld.c プロジェクト: DarkSpiritNET/NeoStats
void AddTLDUser( const Client *u )
{
	const char *country_name;
	const char *country_code;
	TLD *t = NULL;

	if( !gi )
		return;
	country_code = GeoIP_country_code_by_addr( gi, u->hostip );
	if( country_code )
	{
		t = lnode_find( tldstatlist, country_code, FindTLD );
		if( !t )
		{
			country_name = GeoIP_country_name_by_addr( gi, u->hostip );
			t = ns_calloc( sizeof( TLD ) );
			strlcpy( t->tld, country_code, 5 );
			strlcpy( t->country, country_name, 32 );
			lnode_create_append( tldstatlist, t );
		}
	}
	else
	{
		t = lnode_find( tldstatlist, UNKNOWN_COUNTRY_CODE, FindTLD );
	}
	IncStatistic( &t->users );
}
コード例 #3
0
ファイル: CslGeoIP.cpp プロジェクト: aurhat/cubelister
const char* CslGeoIP::GetCountryCodeByAddr(const char *host)
{
    CslGeoIP& self = GetInstance();

    if (!g_geoIP)
        return NULL;

    GeoIPRecord *r = NULL;
    const char *code = NULL;

    switch (self.m_type)
    {
        case GEOIP_COUNTRY:
            code = GeoIP_country_code_by_addr(g_geoIP, host);
            break;
        case GEOIP_CITY:
            if ((r = GeoIP_record_by_addr(g_geoIP, host)))
            {
                code = r->country_code;
                GeoIPRecord_delete(r);
            }
            break;
    }

    return code;
}
コード例 #4
0
ファイル: vmod_geoip.c プロジェクト: b3cft/geoip-vmod
const char *
vmod_country(struct sess *sp, const char *ip)
{
    const char *country = NULL;
    char *cp;

    if (!gi) {
        gi = GeoIP_new(GEOIP_STANDARD);
        if (gi) {
            WSP(sp, SLT_VCL_Log, "GeoIP database was loaded on request.");
        } else {
            WSP(sp, SLT_VCL_Log, "GeoIP database was not loaded on request.");
        }
    }
    if (gi) {
      country = GeoIP_country_code_by_addr(gi, ip);
    }
    if (!country) {
      country= unknownCountry;
    }

    char lowerCountry[2];
    strcpy(lowerCountry, country);
    strtolower(lowerCountry);

    cp= WS_Dup(sp->wrk->ws, (const char *)lowerCountry);

    return(cp);
}
コード例 #5
0
ファイル: GeoIPTools.cpp プロジェクト: alex43dm/ad
/** Возвращает двухбуквенный код страны по ``ip``.
    Если по какой-либо причине страну определить не удалось, возвращается
    пустая строка
*/
std::string country_code_by_addr(const std::string &ip)
{
    if (!GeoCountry())
        return "";

    const char *country = GeoIP_country_code_by_addr(GeoCountry(), ip.c_str());
    return country? country : "";
}
コード例 #6
0
ファイル: m_geoip.cpp プロジェクト: Shawn-Smith/InspIRCd
	void SetExt(LocalUser* user)
	{
		const char* c = GeoIP_country_code_by_addr(gi, user->GetIPString().c_str());
		if (!c)
			c = "UNK";

		std::string* cc = new std::string(c);
		ext.set(user, cc);
	}
コード例 #7
0
ファイル: py_GeoIP.c プロジェクト: appneta/maxmind-geoip
static PyObject * GeoIP_country_code_by_addr_Py(PyObject *self, PyObject *args) {
  char * name;
  const char * retval;
  GeoIP_GeoIPObject* GeoIP = (GeoIP_GeoIPObject*)self;
  if (!PyArg_ParseTuple(args, "s", &name)) {
    return NULL;
  }
  retval = GeoIP_country_code_by_addr(GeoIP->gi, name);
  return Py_BuildValue("s", retval);
}
コード例 #8
0
ファイル: vmod_geoip.c プロジェクト: flecoz/geoip-vmod
/**
 * Country code.
 */
VCL_STRING
vmod_country(const struct vrt_ctx *ctx, struct vmod_priv *pp, const char *ip)
{
    const char *country = NULL;
    if (pp->priv)
    {
        struct GeoIP_databases* db = (struct GeoIP_databases*)pp->priv;
        if (db && db->country)
            country = GeoIP_country_code_by_addr(db->country, ip);
    }
    if (!country)
        country = unknownCountry;
    return WS_Copy(ctx->ws, country, -1);
}
コード例 #9
0
ファイル: extension.cpp プロジェクト: dvarnai/simillimum
static cell_t sm_Geoip_Code2(IPluginContext *pCtx, const cell_t *params)
{
	char *ip;
	const char *ccode;

	pCtx->LocalToString(params[1], &ip);
	StripPort(ip);

	ccode = GeoIP_country_code_by_addr(gi, ip);

	pCtx->StringToLocal(params[2], 3, ccode ? ccode : "");

	return ccode ? 1 : 0;
}
コード例 #10
0
ファイル: tld.c プロジェクト: DarkSpiritNET/NeoStats
void DelTLDUser( const Client * u )
{
	const char *country_code;
	TLD *t = NULL;
	
	SET_SEGV_LOCATION();
	if( !gi )
		return;
	country_code = GeoIP_country_code_by_addr( gi, u->hostip );
	if( country_code )
		t = lnode_find( tldstatlist, country_code, FindTLD );
	else
		t = lnode_find( tldstatlist, UNKNOWN_COUNTRY_CODE, FindTLD );
	DecStatistic( &t->users );		
}
コード例 #11
0
ファイル: geoacl.c プロジェクト: abieuzent/iaxproxy
int geo_acl_check(struct sockaddr_in *sin, char *allowed_countries, char *peername)
{
	GeoIP * gi;
        const char * returnedCountry;
        gi = GeoIP_open("/opt/GeoIP/share/GeoIP/GeoIP.dat", GEOIP_STANDARD | GEOIP_CHECK_CACHE);
	int retValue = 0;
	int j, i=0; // used to iterate through array
	char lookup[255];
    	char *token[86];
        if (gi == NULL) {
                ast_log(LOG_WARNING, "Failed to open GeoIP Lookup database - ignoring GeoACL");
        } else {
		if((allowed_countries == NULL) || (strlen(allowed_countries) == 0) ) {
			ast_log(LOG_NOTICE, "GeoACL - Peer %s does not have allowed/denied countries defined, ignoring check\n", peername);
		} else {
                	ast_log(LOG_DEBUG, "Using %s for allowed geo acl list\n", allowed_countries);
			returnedCountry = GeoIP_country_code_by_addr(gi,ast_inet_ntoa(sin->sin_addr));
	                if (returnedCountry == NULL) {
        	                ast_log(LOG_WARNING, "GeoACL Lookup failed for '%s' - ignoring GeoACL\n", ast_inet_ntoa(sin->sin_addr));
             	   	} else {
				// Now we default to deny since we know what they want and where the IP is from 
				strcpy(lookup, allowed_countries);
				retValue = 1;			
				//ast_log(LOG_NOTICE, "GeoACL - value of allowed_countries is %s", allowed_countries);						
				token[0] = strtok (lookup,",");
  				while(token[i]!= NULL) {   //ensure a pointer was found
        				i++;
        				token[i] = strtok(NULL, ","); //continue to tokenize the string
    				}
  				for(j = 0; j <= i-1; j++) {
			//		ast_log(LOG_DEBUG, "Checking token %s", token[j]);
					if (strncmp(returnedCountry, token[j], 2) == 0) {
						retValue = 0;
					}
				}
				if (retValue == 1)  {
					ast_log(LOG_NOTICE, "GeoACL - peer '%s' failed ACL check.  Allowed from %s but connected from %s\n", peername, allowed_countries, returnedCountry);
				} else {
                	       		 ast_log(LOG_NOTICE, "GeoACL passed for peer '%s' - connected from '%s'\n", peername, returnedCountry);
                		}
			}
		}
        }
        // Free resources
        GeoIP_delete(gi);
	return retValue;
}
コード例 #12
0
ファイル: m_geoip.cpp プロジェクト: Adam-/inspircd
	std::string* SetExt(User* user)
	{
		const char* code = NULL;
		switch (user->client_sa.family())
		{
			case AF_INET:
				code = GeoIP_country_code_by_addr(ipv4db, user->GetIPString().c_str());
				break;

			case AF_INET6:
				code = GeoIP_country_code_by_addr_v6(ipv6db, user->GetIPString().c_str());
				break;
		}

		ext.set(user, code ? code : "UNK");
		return ext.get(user);
	}
コード例 #13
0
ファイル: serverinfo.cpp プロジェクト: sfroberg/CyberDragon
ServerInfo::ServerInfo(MainWindow* m, QWidget *parent) :
    QWidget(parent),mainWindow(m),gi(NULL),latitude(0.0),longitude(0.0),
    settingsFile(QLatin1String("config.ini")),
    ui(new Ui::ServerInfo)
{

    qDebug() << __PRETTY_FUNCTION__ << " called ...";

    ui->setupUi(this);


/*****************************************/
/* GeoIP sanity checking */
/*****************************************/

/* FIXME: Proxy checker module (worker.cpp) already loads GeoIP.dat databse.
 *
 * AFAIK, GeoLiteCity.dat also provides country like GeoIP.dat.
 * So in theory you should only need GeoLiteCity.dat database and not both
 * (GeoIP.dat and GeoLiteCity.dat). Otherwise this is a waste of disk space and RAM.
 *
 * Just have to decide where to load & initialize GeoLiteCity.dat so that *both*
 * modules (this and worker.cpp)can share it ... */

    if(this->gi == NULL) {
        this->gi = GeoIP_open("./GeoLiteCity.dat",GEOIP_INDEX_CACHE | GEOIP_CHECK_CACHE);
        if(gi == NULL) {
            qDebug() << "Error opening database!!!";
        }

        /* make sure GeoIP deals with invalid query gracefully */
        if (GeoIP_country_code_by_addr(this->gi, NULL) != NULL) {
            qDebug() <<  "Invalid Query test failed, got non NULL, expected NULL";
        }

        if (GeoIP_country_code_by_name(this->gi, NULL) != NULL) {
            qDebug() << "Invalid Query test failed, got non NULL, expected NULL";
        }
    }
}
コード例 #14
0
ファイル: geoip.c プロジェクト: foolean/stonesh
/*@null@*/ 
const char *getcountrybyaddr( char *address, char *geoip_data_file )
{
    const char  *country_code = NULL;
    char        *data_file;
    GeoIP       *gi;

    /* set the data file */
    data_file = ( geoip_data_file != NULL ) ? geoip_data_file : GEOIP_DAT;

    /* open the GeoIP database */
    gi = GeoIP_open( data_file, GEOIP_STANDARD );
    if ( gi != NULL ) { 
        /* Get the Country Code for the address */
        country_code = GeoIP_country_code_by_addr( gi, address );

        /* close the GeoIP database */
        GeoIP_delete( gi );
    }
    /*@-mustfreefresh@*/
    return( country_code );
    /*@+mustfreefresh@*/
}
コード例 #15
0
ファイル: geoip.c プロジェクト: 584251395/tools
int main(void)
{
      const char *ipAddress = "193.140.74.29";
      char expectedCountry[3];
      const char *returnedCountry;
      GeoIP *gi;
      int i;
 
      if (0 == i) {
	  /* Read from filesystem, check for updated file */
	  gi = GeoIP_open("/usr/share/GeoIP/GeoIP.dat",  GEOIP_STANDARD | GEOIP_CHECK_CACHE);
      } else {
	  /* Read from memory, faster but takes up more memory */
	  gi = GeoIP_open("/usr/share/GeoIP/GeoIP.dat", GEOIP_MEMORY_CACHE);
      }

      if (gi == NULL) {
	fprintf(stderr, "Error opening database\n");
	exit(1);
      }
  
      returnedCountry = GeoIP_country_code_by_addr(gi, NULL);
      if (returnedCountry != NULL) {
	  fprintf(stderr, "Invalid Query test failed, got non NULL, expected NULL\n");
	  exit(EXIT_FAILURE);  
      }
  
      returnedCountry = GeoIP_country_code_by_name(gi, NULL);
      if (returnedCountry != NULL) {
	fprintf(stderr,"Invalid Query test failed, got non NULL, expected NULL\n");
      }
  
      returnedCountry = GeoIP_country_code3_by_addr(gi, ipAddress);
      printf("%s => %s\n", ipAddress, returnedCountry);
      
      return 0;
}
コード例 #16
0
ファイル: IP2Country.cpp プロジェクト: geekt/amule
const CountryData& CIP2Country::GetCountryData(const wxString &ip)
{
	// Should prevent the crash if the GeoIP database does not exists
	if (m_geoip == NULL) {
		CountryDataMap::iterator it = m_CountryDataMap.find(wxString(wxT("unknown")));
		it->second.Name = wxT("?");
		return it->second;
	}

	// wxString::MakeLower() fails miserably in Turkish localization with their dotted/non-dotted 'i's
	// So fall back to some good ole C string processing.
	std::string strCode;
	const char * c = GeoIP_country_code_by_addr(m_geoip, unicode2char(ip));
	if (!c) {
		c = "unknown";
	}
	for ( ; *c; c++) {
		strCode += ((*c >= 'A' && *c <= 'Z') ? *c + 'a' - 'A' : *c);
	}

	const wxString CCode(strCode.c_str(), wxConvISO8859_1);

	CountryDataMap::iterator it = m_CountryDataMap.find(CCode);
	if (it == m_CountryDataMap.end()) {
		// Show the code and ?? flag
		it = m_CountryDataMap.find(wxString(wxT("unknown")));
		wxASSERT(it != m_CountryDataMap.end());
		if (CCode.IsEmpty()) {
			it->second.Name = wxT("?");
		} else{
			it->second.Name = CCode;
		}
	}

	return it->second;
}
コード例 #17
0
ファイル: test-geoip.c プロジェクト: Asinox/sinatra-geoip
int main () {
  FILE *f;
  char ipAddress[30];
  char expectedCountry[3];
  char expectedCountry3[4];
  const char * returnedCountry;
	GeoIP * gi;
	int failed = 0;
	int test_num = 1;

	int i;
	for (i = 0; i < 2; ++i) {
		if (0 == i) {
			/* Read from filesystem, check for updated file */
			gi = GeoIP_open(SRCDIR"/data/GeoIP.dat", GEOIP_STANDARD | GEOIP_CHECK_CACHE);
		} else {
			/* Read from memory, faster but takes up more memory */
			gi = GeoIP_open(SRCDIR"/data/GeoIP.dat", GEOIP_MEMORY_CACHE);
		}

		if (gi == NULL) {
			fprintf(stderr, "Error opening database\n");
			exit(1);
		}

		/* make sure GeoIP deals with invalid query gracefully */
		returnedCountry = GeoIP_country_code_by_addr(gi,NULL);
		if (returnedCountry != NULL) {
			fprintf(stderr,"Invalid Query test failed, got non NULL, expected NULL\n");
			failed = 1;
		}

		returnedCountry = GeoIP_country_code_by_name(gi,NULL);
		if (returnedCountry != NULL) {
			fprintf(stderr,"Invalid Query test failed, got non NULL, expected NULL\n");
			failed = 1;
		}

		f = fopen(SRCDIR"/test/country_test.txt","r");

		while (fscanf(f, "%s%s%s", ipAddress, expectedCountry, expectedCountry3) != EOF) {
			returnedCountry = GeoIP_country_code_by_addr(gi,ipAddress);
			if (returnedCountry == NULL || strcmp(returnedCountry, expectedCountry) != 0) {
				fprintf(stderr,"Test addr %d for %s failed, got %s, expected %s\n",test_num,ipAddress,returnedCountry,expectedCountry);
				failed = 1;
			}
			returnedCountry = GeoIP_country_code_by_name(gi,ipAddress);
			if (returnedCountry == NULL || strcmp(returnedCountry, expectedCountry) != 0) {
				fprintf(stderr,"Test name %d for %s failed, got %s, expected %s\n",test_num,ipAddress,returnedCountry,expectedCountry);
				failed = 1;
			}
			returnedCountry = GeoIP_country_code3_by_addr(gi,ipAddress);
			if (returnedCountry == NULL || strcmp(returnedCountry, expectedCountry3) != 0) {
				fprintf(stderr,"Test addr %d for %s failed, got %s, expected %s\n",test_num,ipAddress,returnedCountry,expectedCountry);
				failed = 1;
			}
			returnedCountry = GeoIP_country_code3_by_name(gi,ipAddress);
			if (returnedCountry == NULL || strcmp(returnedCountry, expectedCountry3) != 0) {
				fprintf(stderr,"Test name %d for %s failed, got %s, expected %s\n",test_num,ipAddress,returnedCountry,expectedCountry);
				failed = 1;
			}
			test_num++;
		}
		fclose(f);

		f = fopen(SRCDIR"/test/country_test2.txt","r");
		while (fscanf(f, "%s%s", ipAddress, expectedCountry ) != EOF) {
			returnedCountry = GeoIP_country_code_by_addr(gi,ipAddress);
			if (returnedCountry == NULL || strcmp(returnedCountry, expectedCountry) != 0) {
				fprintf(stderr,"Test addr %d %s failed, got %s, expected %s\n",test_num,ipAddress,returnedCountry,expectedCountry);
				failed = 1;
			}
			test_num++;
		}
		fclose(f);

		f = fopen(SRCDIR"/test/country_test_name.txt","r");
		while (fscanf(f, "%s%s", ipAddress, expectedCountry) != EOF) {
			returnedCountry = GeoIP_country_code_by_name(gi,ipAddress);
			if (returnedCountry == NULL || strcmp(returnedCountry, expectedCountry) != 0) {
				fprintf(stderr,"Test addr %d %s failed, got %s, expected %s\n",test_num,ipAddress,returnedCountry,expectedCountry);
				failed = 1;
			}
			test_num++;
		}

		fclose(f);
		GeoIP_delete(gi);
	}
	return failed;
}
コード例 #18
0
ファイル: geo.c プロジェクト: wikimedia/analytics-udp-filters
char *geo_lookup(GeoIP *gi, char *ipaddr, int bird) {
	/*
	 * Lookup the country_code by ip address, we can
	 * extend this in the future with more granular data
	 * such as region,city or even zipcode.
	 */
	static char area[MAX_BUF_LENGTH];

	// set the charset to UTF8
	GeoIP_set_charset(gi, GEOIP_CHARSET_UTF8);

	switch(bird){
		case COUNTRY: {
			const char *country= GeoIP_country_code_by_addr(gi, ipaddr);
			if (country==NULL){
				strncpy(area, unknown_geography, MAX_BUF_LENGTH);
			} else {
				strncpy(area, country, MAX_BUF_LENGTH);
			}

		}
		break;

		case REGION:{
			GeoIPRegion *gir;
			gir=GeoIP_region_by_addr(gi,ipaddr);
			if(gir == NULL || strlen(gir->region)==0){
				strncpy(area, unknown_geography, MAX_BUF_LENGTH);
			} else {
				strncpy(area, gir->region, MAX_BUF_LENGTH);
			}

			if(gir != NULL) {
				GeoIPRegion_delete(gir);
			}
			break;
		}

		case CITY:{
			GeoIPRecord *grecord;
			char *city;
			int mustFreeCity = 0;
			grecord = GeoIP_record_by_addr(gi, ipaddr);
			if (grecord !=NULL){
				if (grecord->city == NULL){
					strncpy(area, unknown_geography, MAX_BUF_LENGTH);
				} else {
					int len = strlen(grecord->city);
					city = strdup(grecord->city);
					mustFreeCity = 1;
					strncpy(area,city, MAX_BUF_LENGTH);
					replace_space_with_underscore(area, len);
				}
				if (mustFreeCity) {
					free(city);
				}
				GeoIPRecord_delete(grecord);
			} else {
				strncpy(area, unknown_geography, MAX_BUF_LENGTH);
			}
			break;
		}

		case LAT_LON: {
			GeoIPRecord *grecord;
			grecord = GeoIP_record_by_addr(gi, ipaddr);
			if (grecord!=NULL){
				snprintf(area, MAX_BUF_LENGTH, "%f,%f", grecord->latitude, grecord->longitude);
				GeoIPRecord_delete(grecord);
			} else {
				strncpy(area, unknown_geography, MAX_BUF_LENGTH);
			}
			break;
		}

		case EVERYTHING: {
			GeoIPRecord *grecord;
			char *country = unknown_geography, *region = unknown_geography, *city = unknown_geography;
			int mustFreeCity = 0;
			float lat = 0.0, lon = 0.0;
			grecord = GeoIP_record_by_addr(gi, ipaddr);
			if (grecord != NULL) {
				if (grecord->city != NULL) {
					city = strdup(grecord->city);
					mustFreeCity = 1;
				}
				replace_space_with_underscore(city, strlen(city));

				if (grecord->region != NULL) {
					region = grecord->region;
				}
				if (grecord->country_code != NULL) {
					country = grecord->country_code;
				}
				lat = grecord->latitude;
				lon = grecord->longitude;
			}
			snprintf(area, MAX_BUF_LENGTH, "%s|%s|%s|%f,%f", country, region, city, lat, lon);

			if (grecord != NULL) {
				GeoIPRecord_delete(grecord);
			}

			if (mustFreeCity) {
				free(city);
			}
			break;
		}

		default:
			break;
	}
	return area;
}
コード例 #19
0
ファイル: GeoIPUpdate.c プロジェクト: Asinox/sinatra-geoip
short int GeoIP_update_database_general (char * user_id,char * license_key,char *data_base_type, int verbose,char ** client_ipaddr, void (*f)( char *)) {
	struct hostent *hostlist;
	int sock;
	char * buf;
	struct sockaddr_in sa;
	int offset = 0, err;
	char * request_uri;
	char * compr;
	unsigned long comprLen;
	FILE *comp_fh, *cur_db_fh, *gi_fh;
	gzFile gz_fh;
	char * file_path_gz, * file_path_test;
	MD5_CONTEXT context;
	MD5_CONTEXT context2;
	unsigned char buffer[1024], digest[16] ,digest2[16];
	char hex_digest[33] = "0000000000000000000000000000000\0";
	char hex_digest2[33] = "0000000000000000000000000000000\0";
	unsigned int i;
	char *f_str;
	GeoIP * gi;
	char * db_info;
	char *ipaddress;
	char *geoipfilename;
	char *tmpstr;
	int dbtype;
	int lookupresult = 1;
	char block[BLOCK_SIZE];
	int block_size = BLOCK_SIZE;
	size_t len;
	size_t request_uri_len;
	size_t size;

	hostlist = GeoIP_get_host_or_proxy();

	if (hostlist == NULL)
		return GEOIP_DNS_ERR;

	if (hostlist->h_addrtype != AF_INET)
		return GEOIP_NON_IPV4_ERR;
	if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return GEOIP_SOCKET_OPEN_ERR;
	}

	memset(&sa, 0, sizeof(struct sockaddr_in));
	sa.sin_port = htons(GeoIPHTTPPort);
	memcpy(&sa.sin_addr, hostlist->h_addr_list[0], hostlist->h_length);
	sa.sin_family = AF_INET;
	
	if (verbose == 1) {
		GeoIP_printf(f,"Connecting to MaxMind GeoIP server\n");
		GeoIP_printf(f, "via Host or Proxy Server: %s:%d\n", hostlist->h_name, GeoIPHTTPPort);
	}
	
	if (connect(sock, (struct sockaddr *)&sa, sizeof(struct sockaddr))< 0)
		return GEOIP_CONNECTION_ERR;
	request_uri = malloc(sizeof(char) * (strlen(license_key) + strlen(GeoIPHTTPRequestMD5)+1036));
	if (request_uri == NULL)
		return GEOIP_OUT_OF_MEMORY_ERR;

	/* get the file name from a web page using the product id */
	sprintf(request_uri,GeoIPHTTPRequestFilename,GeoIPProxyHTTP,GeoIPProxiedHost,data_base_type,GeoIPUpdateHost);
	if (verbose == 1) {
		GeoIP_printf(f, "sending request %s \n",request_uri);
	}
	send(sock, request_uri, strlen(request_uri),0); /* send the request */
	free(request_uri);
	buf = malloc(sizeof(char) * (block_size+4));
	if (buf == NULL)
		return GEOIP_OUT_OF_MEMORY_ERR;
	offset = 0;
	for (;;){
		int amt;
		amt = recv(sock, &buf[offset], block_size,0); 
		if (amt == 0){
			break;
		} else if (amt == -1) {
			free(buf);
			return GEOIP_SOCKET_READ_ERR;
		}
		offset += amt;
		buf = realloc(buf, offset + block_size + 4);
	}
	buf[offset] = 0;
	offset = 0;
	tmpstr = strstr(buf, "\r\n\r\n") + 4;
	if (tmpstr[0] == '.' || strchr(tmpstr, '/') != NULL) {
		free(buf);
		return GEOIP_INVALID_SERVER_RESPONSE;
	}
	geoipfilename = _GeoIP_full_path_to(tmpstr);
	free(buf);

	/* print the database product id and the database filename */
	if (verbose == 1){
		GeoIP_printf(f, "database product id %s database file name %s \n",data_base_type,geoipfilename);
	}
	_GeoIP_setup_dbfilename();

	/* get MD5 of current GeoIP database file */
	if ((cur_db_fh = fopen (geoipfilename, "rb")) == NULL) {
    GeoIP_printf(f, NoCurrentDB, geoipfilename);
	} else {
		md5_init(&context);
		while ((len = fread (buffer, 1, 1024, cur_db_fh)) > 0)
			md5_write (&context, buffer, len);
		md5_final (&context);
		memcpy(digest,context.buf,16);
		fclose (cur_db_fh);
		for (i = 0; i < 16; i++)
			sprintf (&hex_digest[2*i], "%02x", digest[i]);
    GeoIP_printf(f, MD5Info, hex_digest );
	}
	if (verbose == 1) {
		GeoIP_printf(f,"MD5 sum of database %s is %s \n",geoipfilename,hex_digest);
	}
	if (client_ipaddr[0] == NULL) {
		/* We haven't gotten our IP address yet, so let's request it */
		if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
			free(geoipfilename);
			return GEOIP_SOCKET_OPEN_ERR;
		}

		memset(&sa, 0, sizeof(struct sockaddr_in));
		sa.sin_port = htons(GeoIPHTTPPort);
		memcpy(&sa.sin_addr, hostlist->h_addr_list[0], hostlist->h_length);
		sa.sin_family = AF_INET;

		if (verbose == 1)
			GeoIP_printf(f,"Connecting to MaxMind GeoIP Update server\n");

		/* Download gzip file */
		if (connect(sock, (struct sockaddr *)&sa, sizeof(struct sockaddr))< 0) {
			free(geoipfilename);
			return GEOIP_CONNECTION_ERR;
		}
		request_uri = malloc(sizeof(char) * (strlen(license_key) + strlen(GeoIPHTTPRequestMD5)+1036));
		if (request_uri == NULL) {
			free(geoipfilename);
			return GEOIP_OUT_OF_MEMORY_ERR;
		}

		/* get client ip address from MaxMind web page */
		sprintf(request_uri,GeoIPHTTPRequestClientIP,GeoIPProxyHTTP,GeoIPProxiedHost,GeoIPUpdateHost);
		send(sock, request_uri, strlen(request_uri),0); /* send the request */
		if (verbose == 1) {
			GeoIP_printf(f, "sending request %s", request_uri);
		}
		free(request_uri);
		buf = malloc(sizeof(char) * (block_size+1));
		if (buf == NULL) {
			free(geoipfilename);
			return GEOIP_OUT_OF_MEMORY_ERR;
		}
		offset = 0;

		for (;;){
			int amt;
			amt = recv(sock, &buf[offset], block_size,0); 
			if (amt == 0) {
				break;
			} else if (amt == -1) {
				free(buf);
				return GEOIP_SOCKET_READ_ERR;
			}
			offset += amt;
			buf = realloc(buf, offset+block_size+1);
		}

		buf[offset] = 0;
		offset = 0;
		ipaddress = strstr(buf, "\r\n\r\n") + 4; /* get the ip address */
		ipaddress = malloc(strlen(strstr(buf, "\r\n\r\n") + 4)+5);
		strcpy(ipaddress,strstr(buf, "\r\n\r\n") + 4);
		client_ipaddr[0] = ipaddress;
		if (verbose == 1) {
			GeoIP_printf(f, "client ip address: %s\n",ipaddress);
		}
		free(buf);
		close(sock);
	}

	ipaddress = client_ipaddr[0];

	/* make a md5 sum of ip address and license_key and store it in hex_digest2 */
	request_uri_len = sizeof(char) * 2036;
	request_uri = malloc(request_uri_len);
	md5_init(&context2);
	md5_write (&context2, (byte *)license_key, 12);//add license key to the md5 sum
	md5_write (&context2, (byte *)ipaddress, strlen(ipaddress));//add ip address to the md5 sum
	md5_final (&context2);
	memcpy(digest2,context2.buf,16);
	for (i = 0; i < 16; i++)
		snprintf (&hex_digest2[2*i], 3, "%02x", digest2[i]);// change the digest to a hex digest
	if (verbose == 1) {
		GeoIP_printf(f, "md5sum of ip address and license key is %s \n",hex_digest2);
	}

	/* send the request using the user id,product id, 
	 * md5 sum of the prev database and 
	 * the md5 sum of the license_key and ip address */
	if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return GEOIP_SOCKET_OPEN_ERR;
	}
	memset(&sa, 0, sizeof(struct sockaddr_in));
	sa.sin_port = htons(GeoIPHTTPPort);
	memcpy(&sa.sin_addr, hostlist->h_addr_list[0], hostlist->h_length);
	sa.sin_family = AF_INET;
	if (connect(sock, (struct sockaddr *)&sa, sizeof(struct sockaddr))< 0)
		return GEOIP_CONNECTION_ERR;
	snprintf(request_uri, request_uri_len, GeoIPHTTPRequestMD5,GeoIPProxyHTTP,GeoIPProxiedHost,hex_digest,hex_digest2,user_id,data_base_type);
	send(sock, request_uri, strlen(request_uri),0);
	if (verbose == 1) {
		GeoIP_printf(f, "sending request %s\n",request_uri);
	}

	free(request_uri);

	offset = 0;
	buf = malloc(sizeof(char) * block_size);
	if (buf == NULL)
		return GEOIP_OUT_OF_MEMORY_ERR;

	if (verbose == 1)
		GeoIP_printf(f,"Downloading gzipped GeoIP Database...\n");

	for (;;) {
		int amt;
		amt = recv(sock, &buf[offset], block_size,0);

		if (amt == 0) {
			break;
		} else if (amt == -1) {
			free(buf);
			return GEOIP_SOCKET_READ_ERR;
		}
		offset += amt;
		buf = realloc(buf, offset+block_size);
		if (buf == NULL)
			return GEOIP_OUT_OF_MEMORY_ERR;
	}

	compr = strstr(buf, "\r\n\r\n") + 4;
	comprLen = offset + buf - compr;

	if (strstr(compr, "License Key Invalid") != NULL) {
		if (verbose == 1)
			GeoIP_printf(f,"Failed\n");
		free(buf);
		return GEOIP_LICENSE_KEY_INVALID_ERR;
	} else if (strstr(compr, "No new updates available") != NULL) {
		free(buf);
		GeoIP_printf(f, "%s is up to date, no updates required\n", geoipfilename);
		return GEOIP_NO_NEW_UPDATES;
	} else if (strstr(compr, "Invalid UserId") != NULL){
		free(buf);
		return GEOIP_USER_ID_INVALID_ERR;
	} else if (strstr(compr, "Invalid product ID or subscription expired") != NULL){
		free(buf);
		return GEOIP_PRODUCT_ID_INVALID_ERR;
	}

	if (verbose == 1)
		GeoIP_printf(f,"Done\n");

	GeoIP_printf(f, "Updating %s\n", geoipfilename);

	/* save gzip file */
	file_path_gz = malloc(sizeof(char) * (strlen(geoipfilename) + 4));

	if (file_path_gz == NULL)
		return GEOIP_OUT_OF_MEMORY_ERR;
	strcpy(file_path_gz,geoipfilename);
	strcat(file_path_gz,".gz");
	if (verbose == 1) {
    GeoIP_printf(f, "%s%s", SavingGzip, file_path_gz );
	}
	comp_fh = fopen(file_path_gz, "wb");

	if(comp_fh == NULL) {
		free(file_path_gz);
		free(buf);
		return GEOIP_GZIP_IO_ERR;
	}

	size = fwrite(compr, 1, comprLen, comp_fh);
	fclose(comp_fh);
	free(buf);
        if ( size != comprLen ) {
		return GEOIP_GZIP_IO_ERR;
	}

	if (verbose == 1) {
		GeoIP_printf(f, "download data to a gz file named %s \n",file_path_gz);
		GeoIP_printf(f,"Done\n");
		GeoIP_printf(f,"Uncompressing gzip file ... ");
	}

	file_path_test = malloc(sizeof(char) * (strlen(GeoIPDBFileName[GEOIP_COUNTRY_EDITION]) + 6));
	if (file_path_test == NULL) {
		free(file_path_gz);
		return GEOIP_OUT_OF_MEMORY_ERR;
	}
	strcpy(file_path_test,GeoIPDBFileName[GEOIP_COUNTRY_EDITION]);
	strcat(file_path_test,".test");
	gi_fh = fopen(file_path_test, "wb");
	if(gi_fh == NULL) {
		free(file_path_test);
		free(file_path_gz);
		return GEOIP_TEST_IO_ERR;
	}
	/* uncompress gzip file */
	offset = 0;
	gz_fh = gzopen(file_path_gz, "rb");
	for (;;) {
		int amt;
		amt = gzread(gz_fh, block, block_size);
		if (amt == -1) {
			free(file_path_gz);
			free(file_path_test);
			gzclose(gz_fh);
			fclose(gi_fh);
			return GEOIP_GZIP_READ_ERR;
		}
		if (amt == 0) {
			break;
		}
		if ( amt != fwrite(block,1,amt,gi_fh) ){
			return GEOIP_GZIP_IO_ERR;
		}
	}
	gzclose(gz_fh);
	unlink(file_path_gz);
	free(file_path_gz);
	fclose(gi_fh);

	if (verbose == 1)
		GeoIP_printf(f,"Done\n");

	if (verbose == 1) {
		len = strlen(WritingFile) + strlen(geoipfilename) - 1;
		f_str = malloc(len);
		snprintf(f_str,len,WritingFile,geoipfilename);
		free(f_str);
	}

	/* sanity check */
	gi = GeoIP_open(file_path_test, GEOIP_STANDARD);

	if (verbose == 1)
		GeoIP_printf(f,"Performing santity checks ... ");

	if (gi == NULL) {
		GeoIP_printf(f,"Error opening sanity check database\n");
		return GEOIP_SANITY_OPEN_ERR;
	}


	/* get the database type */
	dbtype = GeoIP_database_edition(gi);
	if (verbose == 1) {
		GeoIP_printf(f, "Database type is %d\n",dbtype);
	}

	/* this checks to make sure the files is complete, since info is at the end
		 dependent on future databases having MaxMind in info (ISP and Organization databases currently don't have info string */

	if ((dbtype != GEOIP_ISP_EDITION)&&
			(dbtype != GEOIP_ORG_EDITION)) {
		if (verbose == 1)
			GeoIP_printf(f,"database_info  ");
		db_info = GeoIP_database_info(gi);
		if (db_info == NULL) {
			GeoIP_delete(gi);
			if (verbose == 1)
				GeoIP_printf(f,"FAIL null\n");
			return GEOIP_SANITY_INFO_FAIL;
		}
		if (strstr(db_info, "MaxMind") == NULL) {
			free(db_info);
			GeoIP_delete(gi);
			if (verbose == 1)
				GeoIP_printf(f,"FAIL maxmind\n");
			return GEOIP_SANITY_INFO_FAIL;
		}
		free(db_info);
		if (verbose == 1)
			GeoIP_printf(f,"PASS  ");
	}

	/* this performs an IP lookup test of a US IP address */
	if (verbose == 1)
		GeoIP_printf(f,"lookup  ");
	if (dbtype == GEOIP_NETSPEED_EDITION) {
		int netspeed = GeoIP_id_by_name(gi,"24.24.24.24");
		lookupresult = 0;
		if (netspeed == GEOIP_CABLEDSL_SPEED){
			lookupresult = 1;
		}
	}
	if (dbtype == GEOIP_COUNTRY_EDITION) {
		/* if data base type is country then call the function
		 * named GeoIP_country_code_by_addr */
		lookupresult = 1;
		if (strcmp(GeoIP_country_code_by_addr(gi,"24.24.24.24"), "US") != 0) {
			lookupresult = 0;
		}
		if (verbose == 1) {
			GeoIP_printf(f,"testing GEOIP_COUNTRY_EDITION\n");
		}
	}
	if (dbtype == GEOIP_REGION_EDITION_REV1) {
		/* if data base type is region then call the function
		 * named GeoIP_region_by_addr */
		GeoIPRegion *r = GeoIP_region_by_addr(gi,"24.24.24.24");
		lookupresult = 0;
		if (r != NULL) {
			lookupresult = 1;
			free(r);
		}
		if (verbose == 1) {
			GeoIP_printf(f,"testing GEOIP_REGION_EDITION\n");
		}
	}
	if (dbtype == GEOIP_CITY_EDITION_REV1) {
		/* if data base type is city then call the function
		 * named GeoIP_record_by_addr */
		GeoIPRecord *r = GeoIP_record_by_addr(gi,"24.24.24.24");
		lookupresult = 0;
		if (r != NULL) {
			lookupresult = 1;
			free(r);
		}
		if (verbose == 1) {
			GeoIP_printf(f,"testing GEOIP_CITY_EDITION\n");
		}
	}
	if ((dbtype == GEOIP_ISP_EDITION)||
			(dbtype == GEOIP_ORG_EDITION)) {
		/* if data base type is isp or org then call the function
		 * named GeoIP_org_by_addr */
		GeoIPRecord *r = (GeoIPRecord*)GeoIP_org_by_addr(gi,"24.24.24.24");
		lookupresult = 0;
		if (r != NULL) {
			lookupresult = 1;
			free(r);
		}
		if (verbose == 1) {
			if (dbtype == GEOIP_ISP_EDITION) {
				GeoIP_printf(f,"testing GEOIP_ISP_EDITION\n");
			}
			if (dbtype == GEOIP_ORG_EDITION) {
				GeoIP_printf(f,"testing GEOIP_ORG_EDITION\n");
			}
		}
	}
	if (lookupresult == 0) {
		GeoIP_delete(gi);
		if (verbose == 1)
			GeoIP_printf(f,"FAIL\n");
		return GEOIP_SANITY_LOOKUP_FAIL;
	}
	GeoIP_delete(gi);
	if (verbose == 1)
		GeoIP_printf(f,"PASS\n");

	/* install GeoIP.dat.test -> GeoIP.dat */
	err = rename(file_path_test, geoipfilename);
	if (err != 0) {
		GeoIP_printf(f,"GeoIP Install error while renaming file\n");
		return GEOIP_RENAME_ERR;
	}

	if (verbose == 1)
		GeoIP_printf(f,"Done\n");
	free(geoipfilename);
	return 0;
}
コード例 #20
0
ファイル: GeoIPUpdate.c プロジェクト: Asinox/sinatra-geoip
short int GeoIP_update_database (char * license_key, int verbose, void (*f)( char * )) {
	struct hostent *hostlist;
	int sock;
	char * buf;
	struct sockaddr_in sa;
	int offset = 0, err;
	char * request_uri;
	char * compr;
	unsigned long comprLen;
	FILE *comp_fh, *cur_db_fh, *gi_fh;
	gzFile gz_fh;
	char * file_path_gz, * file_path_test;
	MD5_CONTEXT context;
	unsigned char buffer[1024], digest[16];
	char hex_digest[33] = "00000000000000000000000000000000\0";
	unsigned int i;
	GeoIP * gi;
	char * db_info;
	char block[BLOCK_SIZE];
	int block_size = BLOCK_SIZE;
	size_t len;
	size_t written;
	_GeoIP_setup_dbfilename();

	/* get MD5 of current GeoIP database file */
	if ((cur_db_fh = fopen (GeoIPDBFileName[GEOIP_COUNTRY_EDITION], "rb")) == NULL) {
    GeoIP_printf(f,"%s%s",  NoCurrentDB, GeoIPDBFileName[GEOIP_COUNTRY_EDITION]);
	} else {
		md5_init(&context);
		while ((len = fread (buffer, 1, 1024, cur_db_fh)) > 0)
			md5_write (&context, buffer, len);
		md5_final (&context);
		memcpy(digest,context.buf,16);
		fclose (cur_db_fh);
		for (i = 0; i < 16; i++) {
			// "%02x" will write 3 chars
			snprintf (&hex_digest[2*i], 3, "%02x", digest[i]);
		}
    GeoIP_printf(f, MD5Info, hex_digest);
	}

	hostlist = GeoIP_get_host_or_proxy();

	if (hostlist == NULL)
		return GEOIP_DNS_ERR;

	if (hostlist->h_addrtype != AF_INET)
		return GEOIP_NON_IPV4_ERR;

	if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return GEOIP_SOCKET_OPEN_ERR;
	}

	memset(&sa, 0, sizeof(struct sockaddr_in));
	sa.sin_port = htons(GeoIPHTTPPort);
	memcpy(&sa.sin_addr, hostlist->h_addr_list[0], hostlist->h_length);
	sa.sin_family = AF_INET;

	if (verbose == 1){
		GeoIP_printf(f,"Connecting to MaxMind GeoIP Update server\n");
		GeoIP_printf(f, "via Host or Proxy Server: %s:%d\n", hostlist->h_name, GeoIPHTTPPort);
	}	

	/* Download gzip file */
	if (connect(sock, (struct sockaddr *)&sa, sizeof(struct sockaddr))< 0)
		return GEOIP_CONNECTION_ERR;

	request_uri = malloc(sizeof(char) * (strlen(license_key) + strlen(GeoIPHTTPRequest)+36));
	if (request_uri == NULL)
		return GEOIP_OUT_OF_MEMORY_ERR;
	sprintf(request_uri,GeoIPHTTPRequest,GeoIPProxyHTTP,GeoIPProxiedHost,license_key, hex_digest);
	send(sock, request_uri, strlen(request_uri),0);
	free(request_uri);

	buf = malloc(sizeof(char) * block_size);
	if (buf == NULL)
		return GEOIP_OUT_OF_MEMORY_ERR;

	if (verbose == 1)
		GeoIP_printf(f,"Downloading gzipped GeoIP Database...\n");

	for (;;) {
		int amt;
		amt = recv(sock, &buf[offset], block_size,0);
		if (amt == 0) {
			break;
		} else if (amt == -1) {
			free(buf);
			return GEOIP_SOCKET_READ_ERR;
		}
		offset += amt;
		buf = realloc(buf, offset+block_size);
		if (buf == NULL)
			return GEOIP_OUT_OF_MEMORY_ERR;
	}

	compr = strstr(buf, "\r\n\r\n") + 4;
	comprLen = offset + buf - compr;

	if (strstr(compr, "License Key Invalid") != NULL) {
		if (verbose == 1)
			GeoIP_printf(f,"Failed\n");
		free(buf);
		return GEOIP_LICENSE_KEY_INVALID_ERR;
	} else if (strstr(compr, "Invalid product ID or subscription expired") != NULL){
		free(buf);
		return GEOIP_PRODUCT_ID_INVALID_ERR;
	} else if (strstr(compr, "No new updates available") != NULL) {
		free(buf);
		return GEOIP_NO_NEW_UPDATES;
	}

	if (verbose == 1)
		GeoIP_printf(f,"Done\n");

	/* save gzip file */
	file_path_gz = malloc(sizeof(char) * (strlen(GeoIPDBFileName[GEOIP_COUNTRY_EDITION]) + 4));
	if (file_path_gz == NULL)
		return GEOIP_OUT_OF_MEMORY_ERR;
	strcpy(file_path_gz,GeoIPDBFileName[GEOIP_COUNTRY_EDITION]);
	strcat(file_path_gz,".gz");
	if (verbose == 1) {
    GeoIP_printf(f, SavingGzip, file_path_gz);
	}
	comp_fh = fopen(file_path_gz, "wb");

	if(comp_fh == NULL) {
		free(file_path_gz);
		free(buf);
		return GEOIP_GZIP_IO_ERR;
	}

	written = fwrite(compr, 1, comprLen, comp_fh);
	fclose(comp_fh);
	free(buf);

        if ( written != comprLen )
		return GEOIP_GZIP_IO_ERR;

	if (verbose == 1)
		GeoIP_printf(f,"Done\n");

	if (verbose == 1)
		GeoIP_printf(f,"Uncompressing gzip file ... ");

	/* uncompress gzip file */
	gz_fh = gzopen(file_path_gz, "rb");
	file_path_test = malloc(sizeof(char) * (strlen(GeoIPDBFileName[GEOIP_COUNTRY_EDITION]) + 6));
	if (file_path_test == NULL)
		return GEOIP_OUT_OF_MEMORY_ERR;
	strcpy(file_path_test,GeoIPDBFileName[GEOIP_COUNTRY_EDITION]);
	strcat(file_path_test,".test");
	gi_fh = fopen(file_path_test, "wb");

	if(gi_fh == NULL) {
		free(file_path_test);
		return GEOIP_TEST_IO_ERR;
	}
	for (;;) {
		int amt;
		amt = gzread(gz_fh, block, block_size);
		if (amt == -1) {
			free(file_path_test);
			fclose(gi_fh);
			gzclose(gz_fh);
			return GEOIP_GZIP_READ_ERR;
		}
		if (amt == 0) {
			break;
		}
		if ( fwrite(block,1,amt,gi_fh) != amt ){
			free(file_path_test);
			fclose(gi_fh);
			gzclose(gz_fh);
			return GEOIP_GZIP_READ_ERR;
		}
	}
	gzclose(gz_fh);
	unlink(file_path_gz);
	free(file_path_gz);
	fclose(gi_fh);

	if (verbose == 1)
		GeoIP_printf(f,"Done\n");

	if (verbose == 1) {
    GeoIP_printf(f, WritingFile, GeoIPDBFileName[GEOIP_COUNTRY_EDITION]);
	}

	/* sanity check */
	gi = GeoIP_open(file_path_test, GEOIP_STANDARD);

	if (verbose == 1)
		GeoIP_printf(f,"Performing santity checks ... ");

	if (gi == NULL) {
		GeoIP_printf(f,"Error opening sanity check database\n");
		return GEOIP_SANITY_OPEN_ERR;
	}

	/* this checks to make sure the files is complete, since info is at the end */
	/* dependent on future databases having MaxMind in info */
	if (verbose == 1)
		GeoIP_printf(f,"database_info  ");
	db_info = GeoIP_database_info(gi);
	if (db_info == NULL) {
		GeoIP_delete(gi);
		if (verbose == 1)
			GeoIP_printf(f,"FAIL\n");
		return GEOIP_SANITY_INFO_FAIL;
	}
	if (strstr(db_info, "MaxMind") == NULL) {
		free(db_info);
		GeoIP_delete(gi);
		if (verbose == 1)
			GeoIP_printf(f,"FAIL\n");
		return GEOIP_SANITY_INFO_FAIL;
	}
	free(db_info);
	if (verbose == 1)
		GeoIP_printf(f,"PASS  ");

	/* this performs an IP lookup test of a US IP address */
	if (verbose == 1)
		GeoIP_printf(f,"lookup  ");
	if (strcmp(GeoIP_country_code_by_addr(gi,"24.24.24.24"), "US") != 0) {
		GeoIP_delete(gi);
		if (verbose == 1)
			GeoIP_printf(f,"FAIL\n");
		return GEOIP_SANITY_LOOKUP_FAIL;
	}
	GeoIP_delete(gi);
	if (verbose == 1)
		GeoIP_printf(f,"PASS\n");

	/* install GeoIP.dat.test -> GeoIP.dat */
	err = rename(file_path_test, GeoIPDBFileName[GEOIP_COUNTRY_EDITION]);
	if (err != 0) {
		GeoIP_printf(f,"GeoIP Install error while renaming file\n");
		return GEOIP_RENAME_ERR;
	}

	if (verbose == 1)
		GeoIP_printf(f,"Done\n");

	return 0;
}
コード例 #21
0
ファイル: sniffer.cpp プロジェクト: andrkonin/PACKET_SNIFFER
void
SNIFFER::got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{  
        const struct sniff_ethernet *ethernet;
        const struct sniff_ip *ip;
        const struct sniff_tcp *tcp;
        const u_char *payload;

        int size_ip;
        int size_tcp;
        int size_payload;

        pcnt++;
        sprintf(txtstr," %d ", pcnt);

        str=txtstr;
        if (pcnt<10)
            str+="    ";
        else if (pcnt<100)
            str+="   ";
        else if (pcnt<1000)
            str+="  ";
        else str+=" ";
        //status->append(txtstr);
        //count++;

        ethernet = (struct sniff_ethernet*)(packet);

        ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
        size_ip = IP_HL(ip)*4;
        if (size_ip < 20) {
                sprintf(txtstr,"   * Invalid IP header length: %u bytes", size_ip);
                str+=txtstr;
                //status->append(txtstr);
                return;
        }
        int i,k;

        sprintf(txtstr,"%s", inet_ntoa(ip->ip_src));
        str+=txtstr;
        k=strlen(inet_ntoa(ip->ip_src));
        if (k<15)
        {
            for (i=0;i<15-k;i++)
                str+=" ";
        }

        //status->append(txtstr);
        sprintf(txtstr,"%s", inet_ntoa(ip->ip_dst));
        str+=txtstr;
        k=strlen(inet_ntoa(ip->ip_dst));
        if (k<15)
        {
            for (i=0;i<15-k;i++)
                str+=" ";
        }

        //status->append(txtstr);
        sprintf(txtstr," %d ", header->len);
        str+=txtstr;
        if (header->len<10)
            str+="    ";
        else if (header->len<100)
            str+="   ";
        else if (header->len<1000)
            str+="  ";
        else
            str+=" ";

        ltime=localtime(&header->ts.tv_sec);
        strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
        sprintf(timeS,"  %s.%.6d", timestr, header->ts.tv_usec);
        //sprintf(txtstr,"  time %.6d", header->ts.tv_usec);
        //str+=txtstr;
        //status->append(txtstr);

        //sprintf(txtstr,"       Time: %f", header->ts);
        //status->append(txtstr);

#ifdef WIN32
        country="   (This option is only for Linux)";
#else
        if (scountry=GeoIP_country_code_by_addr(gi,inet_ntoa(ip->ip_src)))
        {
            sprintf(txtstr,"   %s            ",scountry);
            country=txtstr;
        }
        else
            country="   -             ";

        if (dcountry=GeoIP_country_code_by_addr(gi,inet_ntoa(ip->ip_dst)))
        {
            sprintf(txtstr,"%s           ",dcountry);
            country+=txtstr;
        }
        else
            country+="-            ";

#endif

        //if (strlen(txtstr)!=0)
        //str+=txtstr;
        //if (strlen(txtstr)==2)
        //    str+="           ";
        //else
        //    str+="         ";
        //sprintf(txtstr,"%s",GeoIP_country_name_by_addr(gi,inet_ntoa(ip->ip_dst)));
        //str+=txtstr;

        /* determine protocol */

        switch(ip->ip_p) {
                case IPPROTO_TCP:
                        sprintf(txtstr,"   TCP      ");
                        str+=txtstr;
                        str+=timeS;
                        str+=country;
                        //status->append(str);

                        break;
                case IPPROTO_UDP:
                        sprintf(txtstr,"   UDP      ");
                        str+=txtstr;
                        str+=timeS;
                        str+=country;
                        status->append(str);
                        status->append("--------------------------------------------------------------------------------------------------------");
                        return;
                case IPPROTO_ICMP:
                        sprintf(txtstr,"   ICMP     ");
                        str+=txtstr;
                        str+=timeS;
                        str+=country;
                        status->append(str);
                        status->append("--------------------------------------------------------------------------------------------------------");
                        return;
                case IPPROTO_IP:

                        sprintf(txtstr,"   IP       ");
                        str+=txtstr;
                        str+=timeS;
                        str+=country;
                        status->append(str);
                        status->append("--------------------------------------------------------------------------------------------------------");
                        return;
                default:
                        sprintf(txtstr,"   unknown   ");
                        str+=txtstr;

                        str+=timeS;
                        str+=country;
                        status->append(str);
                        status->append("--------------------------------------------------------------------------------------------------------");

                        error=true;
                        result="Unknown protocol";
                        emit onLoad();
                        error=false;


                        return;
        }

        tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
        size_tcp = TH_OFF(tcp)*4;
        if (size_tcp < 20) {
                sprintf(txtstr,"   * Invalid TCP header length: %u bytes", size_tcp);
                status->append(txtstr);
                return;
        }

        sprintf(txtstr,"\nSrc. port: %d\n", ntohs(tcp->th_sport));
        str+=txtstr;
        //status->append(txtstr);
        sprintf(txtstr,"Dst. port: %d", ntohs(tcp->th_dport));
        str+=txtstr;
        status->append(str);

        payload = (u_char *)(packet + SIZE_ETHERNET + size_ip + size_tcp);

        size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp);

        if (size_payload > 0) {
                sprintf(txtstr,"   Payload (%d bytes):", size_payload);
                str+=txtstr;
                status->append(txtstr);

                print_payload(payload, size_payload);
        }
        status->append("--------------------------------------------------------------------------------------------------------");

        return;
}