예제 #1
0
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);
}
예제 #2
0
파일: signals.c 프로젝트: wodim/irc-hispano
VOIDSIG signal_rehash(int signum)
{
#ifdef	POSIX_SIGNALS
    struct sigaction act;
#endif
#ifdef SIGHUP
    if (signum == SIGHUP) {
#endif
        Dadmin *a;
        int i;

        alog(LOG_NORMAL,
             "Received SIGHUP: Saving Databases & Rehash Configuration");
        if (initconf(denora->config, 1, mainconf) == -1) {
            denora->qmsg = calloc(50, 1);
            if (!denora->qmsg) {
                denora->qmsg = sstrdup(langstr(ALOG_ERR_REHASH_NO_MEM));
            } else {
                ircsnprintf(denora->qmsg, sizeof(denora->qmsg), "%s",
                            langstr(ALOG_ERR_REHASH));
            }
            denora->quitting = 1;
            send_event(EVENT_SIGNAL, 2, "SIGHUP", denora->qmsg);
        } else {
            /* Remove all config file admins from admin struct before re-reading config file */
            for (i = 0; i < 1024; i++) {
                for (a = adminlists[i]; a; a = a->next) {
                    if (a->configfile) {
                        free_admin(a);
                    }
                    break;
                }
            }
            merge_confs();
        }
        /* Reload GeoIP db files */
        if (gi) {
			GeoIP_delete(gi);
		}
		if (gi_v6) {
			GeoIP_delete(gi_v6);
		}
	    gi = GeoIP_new(GEOIP_STANDARD);
	    gi_v6 = GeoIP_open_type(GEOIP_COUNTRY_EDITION_V6, GEOIP_STANDARD);
#ifdef	POSIX_SIGNALS
        act.sa_handler = signal_rehash;
        act.sa_flags = 0;

        (void) sigemptyset(&act.sa_mask);
        (void) sigaddset(&act.sa_mask, SIGHUP);
        (void) sigaction(SIGHUP, &act, NULL);
#else
# ifndef _WIN32
        (void) signal(SIGHUP, signal_rehash);   /* sysV -argv */
# endif
#endif
#ifdef SIGHUP
    }
#endif
}
예제 #3
0
파일: GeoIPTools.cpp 프로젝트: alex43dm/ad
/** Возвращает объект GeoIP для определения страны по ip */
GeoIP *GeoCountry()
{
    static GeoIP *geo = 0;
    if (geo)
        return geo;
    geo = GeoIP_new(GEOIP_MEMORY_CACHE);
    return geo;
}
예제 #4
0
static inline void
tf_geoip_init(void)
{
  if (!local_state)
    {
      local_state = g_new0(TFGeoIPState, 1);
      local_state->gi = GeoIP_new(GEOIP_MMAP_CACHE);
    }
}
예제 #5
0
int
init_function(struct vmod_priv *priv, const struct VCL_conf *conf)
{
    if (gi) {
      GeoIP_delete(gi);
    }
    gi = GeoIP_new(GEOIP_STANDARD);
    return (0);
}
예제 #6
0
static void
init_geoip (void)
{
  /* open custom city GeoIP database */
  if (conf.geoip_database != NULL)
    geo_location_data = geoip_open_db (conf.geoip_database);
  /* fall back to legacy GeoIP database */
  else
    geo_location_data = GeoIP_new (conf.geo_db);
}
예제 #7
0
int
init_function(struct vmod_priv *pp, const struct VCL_conf *conf)
{
    pp->priv = malloc(sizeof(struct GeoIP_databases));
    if (!pp->priv)
        return 1;
    struct GeoIP_databases* db = (struct GeoIP_databases*)pp->priv;

    db->country = GeoIP_new(GEOIP_MMAP_CACHE);
    db->org = GeoIP_open(GeoIPDBFileName[GEOIP_ORG_EDITION], GEOIP_MMAP_CACHE);
    db->region = GeoIP_open(GeoIPDBFileName[GEOIP_REGION_EDITION_REV1], GEOIP_MMAP_CACHE);

    pp->free = &free_databases;
    return (0);
}
예제 #8
0
static void geoip_child_init(apr_pool_t * p, server_rec * s)
{
    geoip_server_config_rec *cfg;
    int i, flags;

    cfg = (geoip_server_config_rec *)
        ap_get_module_config(s->module_config, &geoip_module);

    if (cfg->gips) {
        if (cfg->GeoIPFilenames != NULL) {
            for (i = 0; i < cfg->numGeoIPFiles; i++) {
                flags =
                    (cfg->GeoIPFlags2[i] ==
                     GEOIP_UNKNOWN) ? cfg->GeoIPFlags : cfg->GeoIPFlags2[i];
                if (flags & (GEOIP_MEMORY_CACHE | GEOIP_MMAP_CACHE))
                    continue;
                if (cfg->gips[i]) {
                    GeoIP_delete(cfg->gips[i]);
                }
                cfg->gips[i] = GeoIP_open(cfg->GeoIPFilenames[i], flags);

                if (cfg->gips[i]) {
                    if (cfg->GeoIPEnableUTF8) {
                        GeoIP_set_charset(cfg->gips[i], GEOIP_CHARSET_UTF8);
                    }
                } else {
                    ap_log_error(APLOG_MARK, APLOG_ERR, 0,
                                 s,
                                 "[mod_geoip]: Error while opening data file %s",
                                 cfg->GeoIPFilenames[i]);
                    continue;
                }
            }
        } else {
            if (cfg->gips[0])
                GeoIP_delete(cfg->gips[0]);
            cfg->gips[0] = GeoIP_new(GEOIP_STANDARD);
            if (!cfg->gips[0]) {
                ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
                             "[mod_geoip]: Error while opening data file");
            }
            cfg->numGeoIPFiles = 1;
        }
    }
}
예제 #9
0
파일: country-filter.c 프로젝트: aufau/xqf
void geoip_init(void) {
	const char* geoipdat = getenv("xqf_GEOIPDAT");

	if (gi) return; // already initialized

	if (geoipdat)
		gi = GeoIP_open(geoipdat, GEOIP_STANDARD);

	if (!gi)
		gi = GeoIP_new(GEOIP_STANDARD);

	if (gi && geoip_num_countries())
		flags = g_malloc0((MaxCountries+1) *sizeof(struct pixmap)); /*+1-> flag for LAN server*/
	else {
		geoip_done();
		xqf_error("GeoIP initialization failed");
	}
}
예제 #10
0
파일: gdashboard.c 프로젝트: denji/goaccess
/* Geolocation data */
char *
get_geoip_data (const char *data)
{
   const char *location = NULL;

#ifdef HAVE_LIBGEOIP
   const char *addr = data;
   /* Geolocation data */
   GeoIP *gi;
   gi = GeoIP_new (GEOIP_STANDARD);
   if (gi != NULL)
      location = GeoIP_country_name_by_name (gi, addr);
   if (location == NULL)
      location = "Location Unknown";
   if (gi != NULL)
      GeoIP_delete (gi);
#endif
   return (char *) location;
}
예제 #11
0
	void init()
	{
		gi = GeoIP_new(GEOIP_STANDARD);
		if (gi == NULL)
				throw ModuleException("Unable to initialize geoip, are you missing GeoIP.dat?");

		ServerInstance->Modules->AddService(ext);
		Implementation eventlist[] = { I_OnSetConnectClass, I_OnStats };
		ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));

		for (LocalUserList::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); ++i)
		{
			LocalUser* user = *i;
			if ((user->registered == REG_ALL) && (!ext.get(user)))
			{
				SetExt(user);
			}
		}
	}
예제 #12
0
/* initialize geoip once per server ( even virtal server! ) */
static void geoip_server_init(apr_pool_t * p, server_rec * s)
{
    geoip_server_config_rec *cfg;
    int i;
    cfg = (geoip_server_config_rec *)
        ap_get_module_config(s->module_config, &geoip_module);

    if (!cfg->gips) {
        if (cfg->GeoIPFilenames != NULL) {
            cfg->gips = malloc(sizeof(GeoIP *) * cfg->numGeoIPFiles);
            for (i = 0; i < cfg->numGeoIPFiles; i++) {
                cfg->gips[i] =
                    GeoIP_open(cfg->GeoIPFilenames[i],
                               (cfg->GeoIPFlags2[i] ==
                                GEOIP_UNKNOWN) ? cfg->GeoIPFlags
                               : cfg->GeoIPFlags2[i]);

                if (cfg->gips[i]) {
                    if (cfg->GeoIPEnableUTF8) {
                        GeoIP_set_charset(cfg->gips[i], GEOIP_CHARSET_UTF8);
                    }
                } else {
                    ap_log_error(APLOG_MARK, APLOG_ERR, 0,
                                 s,
                                 "[mod_geoip]: Error while opening data file %s",
                                 cfg->GeoIPFilenames[i]);
                    continue;
                }
            }
        } else {
            cfg->gips = malloc(sizeof(GeoIP *));
            cfg->gips[0] = GeoIP_new(GEOIP_STANDARD);
            if (!cfg->gips[0]) {
                ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
                             "[mod_geoip]: Error while opening data file");
            }
            cfg->numGeoIPFiles = 1;
        }
    }

    apr_pool_cleanup_register(p, (void *)cfg, geoip_cleanup, geoip_cleanup);

}
예제 #13
0
static PyObject*
GeoIP_new_Py(PyObject* self, PyObject *args) {
  GeoIP_GeoIPObject* GeoIP;
  int flags;

  if (!PyArg_ParseTuple(args, "i", &flags)) {
    return NULL;
  }

  GeoIP = PyObject_New(GeoIP_GeoIPObject, &GeoIP_GeoIPType);

  GeoIP->gi = GeoIP_new(flags);

  if (!GeoIP->gi) {
    PyErr_SetString(PyGeoIPError,  "Can't create GeoIP->gi object");
    return NULL;
  }

  return (PyObject*)GeoIP;
}
예제 #14
0
vmod_event(VRT_CTX, struct vmod_priv *pp, enum vcl_event_e evt)
{

	CHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);

	if (pp->priv == NULL) {
		xxxassert(evt == VCL_EVENT_LOAD);

		/* The README says:
		 * If GEOIP_MMAP_CACHE doesn't work on a 64bit machine, try
		 * adding * the flag "MAP_32BIT" to the mmap call. MMAP is not
		 * avail for WIN32.
		 */
		pp->priv = GeoIP_new(GEOIP_MMAP_CACHE);
		AN(pp->priv);
		pp->free = (vmod_priv_free_f *)GeoIP_delete;
		GeoIP_set_charset((GeoIP *)pp->priv, GEOIP_CHARSET_UTF8);
	}

	return (0);
}
예제 #15
0
void *openspy_mod_run(modLoadOptions *options) {
  int sd;
  int len;
  char buf[MAX_DATA_SIZE + 1];
  #ifndef _WIN32
  gi = GeoIP_new(GEOIP_STANDARD);
  #else
  WSADATA ws;
  WSAStartup(MAKEWORD(1,0),&ws);
  #endif
  struct sockaddr si_other;
  memcpy(&servoptions,options,sizeof(modLoadOptions));
  socklen_t slen = sizeof(si_other);
  struct sockaddr_in si_me;
  if((sd=socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP)) == -1)
   return NULL;
  memset((char *)&si_me, 0, sizeof(si_me));
  si_me.sin_family = AF_INET;
  si_me.sin_port = htons(QRPORT);
  si_me.sin_addr.s_addr = options->bindIP;
  if(bind(sd,(struct sockaddr *)&si_me,sizeof(si_me)) == -1)
   return NULL;
	struct timeval tv;
  for(;;) {
    memset((char *)&buf,0, sizeof(buf));
    tv.tv_sec = 60;
    tv.tv_usec = 0;
    setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,  sizeof tv);
    len = recvfrom(sd,(char *)&buf,sizeof(buf), 0, (struct sockaddr *)&si_other, &slen);
    if(len < 0) { //timeout, do keep alives and delete clients who have expired
	checkTimeouts();
	continue;
    }
    buf[len] = 0;
//  makeStringSafe((char *)&buf, sizeof(buf));
    handleClient(sd,(struct sockaddr_in *)&si_other,(char *)&buf,len);
  }
	return NULL;
}
예제 #16
0
파일: geoip.c 프로젝트: loveshell/ironbee
/* Called when module is loaded. */
static ib_status_t geoip_init(ib_engine_t *ib, ib_module_t *m, void *cbdata)
{
    IB_FTRACE_INIT();

    ib_status_t rc;

    if (geoip_db == NULL)
    {
        ib_log_debug(ib, "Initializing default GeoIP database...");
        geoip_db = GeoIP_new(GEOIP_MMAP_CACHE);
    }

    if (geoip_db == NULL)
    {
        ib_log_debug(ib, "Failed to initialize GeoIP database.");
        IB_FTRACE_RET_STATUS(IB_EUNKNOWN);
    }

    ib_log_debug(ib, "Initializing GeoIP database complete.");

    ib_log_debug(ib, "Registering handler...");

    rc = ib_hook_tx_register(ib,
                             handle_context_tx_event,
                             geoip_lookup,
                             NULL);

    ib_log_debug(ib, "Done registering handler.");

    if (rc != IB_OK)
    {
        ib_log_debug(ib, "Failed to load GeoIP module.");
        IB_FTRACE_RET_STATUS(rc);
    }

    ib_log_debug(ib, "GeoIP module loaded.");
    IB_FTRACE_RET_STATUS(IB_OK);
}
예제 #17
0
static int
GeoIP_GeoIP_init(PyObject *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = { "filename", "flags", NULL };
    GeoIP_GeoIPObject *GeoIP = (GeoIP_GeoIPObject *)self;
    char *filename = NULL;
    int flags;

    /* For consistency with the C API, positional arguments are in the
       order filename, flags; but it is filename that is optional. */
    if (PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist + 1, &flags)) {
        GeoIP->gi = GeoIP_new(flags);
    } else{
        PyErr_Clear();
        if (PyArg_ParseTupleAndKeywords(args, kwargs, "si", kwlist,
                                        &filename, &flags)) {
            GeoIP->gi = GeoIP_open(filename, flags);
        } else{
            return -1;
        }
    }

    if (!GeoIP->gi) {
        /* Failure is probably due to a system-call-level failure. */
        if (!filename) {
            filename = GeoIPDBFileName[GEOIP_COUNTRY_EDITION];
        }
        PyErr_SetFromErrnoWithFilename(GeoIP_GeoIPError, filename);
        return -1;
    }

#if PY_MAJOR_VERSION >= 3
    GeoIP_set_charset(GeoIP->gi, GEOIP_CHARSET_UTF8);
#endif

    return 0;
}
예제 #18
0
    GeoIP * gi = GeoIP_open_type(PARAM_INT(0), PARAM_INT(1));
    RETURN_NUMBER((SYS_INT)gi)
END_IMPL
//------------------------------------------------------------------------
CONCEPT_FUNCTION_IMPL(GeoIP_open, 2)
    T_STRING(GeoIP_open, 0)
    T_NUMBER(GeoIP_open, 1)

    GeoIP * gi = GeoIP_open(PARAM(0), PARAM_INT(1));
    RETURN_NUMBER((SYS_INT)gi)
END_IMPL
//------------------------------------------------------------------------
CONCEPT_FUNCTION_IMPL(GeoIP_new, 1)
    T_NUMBER(GeoIP_new, 0)

    GeoIP * gi = GeoIP_new(PARAM_INT(0));
    RETURN_NUMBER((SYS_INT)gi)
END_IMPL
//------------------------------------------------------------------------
CONCEPT_FUNCTION_IMPL(GeoIP_country_code_by_name, 2)
    T_HANDLE(GeoIP_country_code_by_name, 0)
    T_STRING(GeoIP_country_code_by_name, 1)

    const char *s = GeoIP_country_code_by_name((GeoIP *)PARAM_INT(0), PARAM(1));
    if (s) {
        RETURN_STRING(s)
    } else {
        RETURN_STRING("")
    }
END_IMPL
//------------------------------------------------------------------------
예제 #19
0
파일: geoip.c 프로젝트: poona/ironbee
/* Called when module is loaded. */
static ib_status_t geoip_init(ib_engine_t *ib, ib_module_t *m, void *cbdata)
{
    ib_status_t    rc;
    GeoIP         *geoip_db = NULL;
    module_data_t *mod_data;

    mod_data = ib_mpool_calloc(ib_engine_pool_main_get(ib),
                               sizeof(*mod_data), 1);
    if (mod_data == NULL) {
        return IB_EALLOC;
    }

    ib_log_debug(ib, "Initializing default GeoIP database...");
    geoip_db = GeoIP_new(GEOIP_MMAP_CACHE);
    if (geoip_db == NULL) {
        ib_log_debug(ib, "Failed to initialize GeoIP database.");
        return IB_EUNKNOWN;
    }

    ib_log_debug(ib, "Initializing GeoIP database complete.");
    ib_log_debug(ib, "Registering handler...");

    /* Store off pointer to our module data structure */
    mod_data->geoip_db = geoip_db;

    /* And point the generic module data at it */
    m->data = mod_data;

    rc = ib_hook_tx_register(ib,
                             handle_context_tx_event,
                             geoip_lookup,
                             mod_data);
    if (rc != IB_OK) {
        ib_log_debug(
            ib,
            "Failed to register tx hook: %s",
            ib_status_to_string(rc));
        return rc;
    }

    ib_log_debug(ib, "Done registering handler.");

    rc = ib_var_source_register(
        &(mod_data->geoip_source),
        ib_engine_var_config_get(ib),
        IB_S2SL("GEOIP"),
        IB_PHASE_NONE, IB_PHASE_NONE
    );
    if (rc != IB_OK) {
        ib_log_warning(ib,
            "GeoIP failed to register \"GEOIP\" var: %s",
            ib_status_to_string(rc)
        );
        /* Continue */
    }

    if (rc != IB_OK) {
        ib_log_debug(ib, "Failed to load GeoIP module.");
        return rc;
    }

    geoip_directive_map[0].cbdata_cb = mod_data;

    ib_log_debug(ib, "GeoIP module loaded.");
    return IB_OK;
}
예제 #20
0
void SNIFFER::open(char *INAME)
{   
    pcnt=0;
    status->append("********************************************************************************************************");
    sprintf(txtstr,"Try to use interface %s:",INAME);
    status->append(txtstr);
    gi=GeoIP_new(GEOIP_STANDARD);
    //char *dev,errbuf[PCAP_ERRBUF_SIZE];

    /* DIRECT*/
      dev="eth0";


    /* CHECKING ALL ACCESSIBLE INTERFACES

    pcap_if_t *alldevsp;

    if (pcap_findalldevs(&alldevsp,errbuf)<0)
    {
        status->append(errbuf);
    }
    while (alldevsp!=NULL)
    {
        status->append(alldevsp->name);
        alldevsp=alldevsp->next;
    }
    */

    /* FIRST WORKABLE INTERFACE

    dev=pcap_lookupdev(errbuf);
    if (dev==NULL)
    {
        status->append("ERROR:Couldn't find default device:");
        status->append(errbuf);
    }
    else
    {
        status->append("Interface chosen:");
        status->append(dev);
    }
    */
    //filter_exp="port 80";

    /* Workable version */

    filter_exp="ip";
    // "udp" "tcp" "icmp"

    //dev=pcap_lookupdev(errbuf);
    dev=INAME;
    if (dev==NULL)
    {
        status->append("Coulnd't find default device or there are no suitable devices.");
        status->append(errbuf);
        interface=false;
        return ;
    }
    status->append(dev);
    if (pcap_lookupnet(dev,&net,&mask,errbuf)==-1)
    {
        status->append("Couldn't get netmask for device");
        status->append(dev);
        status->append(errbuf);
        net=0;
        mask=0;
    }
    handle=pcap_open_live(dev,SNAP_LEN,1,1000,errbuf);
    if (handle==NULL)
    {
        status->append("Coulnd't open device");
        interface=false;
        return ;
    }
    else
        status->append("Device found");
    if (pcap_compile(handle,&fp,filter_exp,0,net)==-1)
    {
        status->append("Couldn't parse filter");
        status->append(filter_exp);
        status->append(pcap_geterr(handle));
        interface=false;
        return ;
    }
    if (pcap_setfilter(handle,&fp)==-1)
    {
        status->append("Couldn't install filter");
        interface=false;
        return ;
    }
    else
    {
        sprintf(txtstr,"Filter set: '%s'",filter_exp);
        status->append(txtstr);
    }
    interface=true;
    status->append("--------------------------------------------------------------------------------------------------------");
    status->append("Num    From:          To:             Len      Protocol   Time              Src.Country   Dst.Country");
    status->append("--------------------------------------------------------------------------------------------------------");
    //packet=pcap_next(handle,&header);


    //status->append(QString::number(header.len,10));
    //pcap_close(handle);




    result="Processing ...";
    emit onLoad();

}
예제 #21
0
파일: mod_geoip.c 프로젝트: Nubisa/JXPanel
static void get_geoip_tables(array_header *geoips, int filter_flags) {
  config_rec *c;

  c = find_config(main_server->conf, CONF_PARAM, "GeoIPTable", FALSE);
  while (c) {
    GeoIP *gi;
    const char *path;
    int flags, use_utf8 = FALSE;

    pr_signals_handle();

    path = c->argv[0];
    flags = *((int *) c->argv[1]);
    use_utf8 = *((int *) c->argv[2]);

    /* Make sure we open tables that are marked with the default
     * GEOIP_STANDARD flag, which has a value of zero.
     */
    if ((flags == GEOIP_STANDARD && filter_flags != GEOIP_STANDARD) || 
        !(flags & filter_flags)) {
      c = find_config_next(c, c->next, CONF_PARAM, "GeoIPTable", FALSE);
      continue;
    } 

    PRIVS_ROOT
    gi = GeoIP_open(path, flags);
    if (gi == NULL &&
        (flags & GEOIP_INDEX_CACHE)) {
      /* Per Bug#3975, a common cause of this error is the fact that some
       * of the Maxmind GeoIP Lite database files simply do not have indexes.
       * So try to open them as standard databases as a fallback.
       */
      pr_log_debug(DEBUG8, MOD_GEOIP_VERSION
        ": unable to open GeoIPTable '%s' using the IndexCache flag "
        "(database lacks index?), retrying without IndexCache flag", path);
      flags &= ~GEOIP_INDEX_CACHE;
      gi = GeoIP_open(path, flags);
    }
    PRIVS_RELINQUISH

    if (gi != NULL) {
      if (use_utf8) {
        GeoIP_set_charset(gi, GEOIP_CHARSET_UTF8); 
      }

      *((GeoIP **) push_array(geoips)) = gi;

      pr_trace_msg(trace_channel, 15, "loaded GeoIP table '%s': %s (type %d)",
        path, GeoIP_database_info(gi), GeoIP_database_edition(gi));

    } else {
      /* XXX Sigh.  Stupid libGeoIP library logs to stdout/stderr, rather
       * than providing a strerror function.  Grr!
       */

      pr_log_pri(PR_LOG_WARNING, MOD_GEOIP_VERSION
        ": warning: unable to open/use GeoIPTable '%s'", path);
    }

    c = find_config_next(c, c->next, CONF_PARAM, "GeoIPTable", FALSE);
  }

  if (geoips->nelts == 0 &&
      static_geoips->nelts == 0 &&
      ((filter_flags == GEOIP_STANDARD) ||
       (filter_flags & GEOIP_CHECK_CACHE))) {
    GeoIP *gi;

    /* Let the library use its own default database file(s), if no others
     * have been configured.
     */

    PRIVS_ROOT
    gi = GeoIP_new(GEOIP_STANDARD);
    PRIVS_RELINQUISH

    if (gi != NULL) {
      *((GeoIP **) push_array(geoips)) = gi;

      pr_trace_msg(trace_channel, 15,
        "loaded default GeoIP table: %s (type %d)",
        GeoIP_database_info(gi), GeoIP_database_edition(gi));

    } else {
      pr_log_pri(PR_LOG_WARNING, MOD_GEOIP_VERSION
        ": warning: unable to open/use default GeoIP library database file(s)");
    }
  }
예제 #22
0
int get_flux(const char * host, struct flux_entry ** results)
{
    struct addrinfo hints, *res, *cur;
    int errcode;
    int count;
    uint32_t isflux=0;
    char * addr_str=NULL;
    void * addr_ptr;
    GeoIP * gi;
    
    *results = NULL;

    memset (&hints, 0, sizeof (hints));
//    memset (&addr_str, 0, sizeof(addr_str));

    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags |= AI_CANONNAME;

    errcode = getaddrinfo (host, NULL, &hints, &res);
    if (errcode < 0)
    {
        return -1;
    }

    /* count hints and allocate return buffer
     */
    for (count = 1, cur = res; cur; cur = cur->ai_next, ++count)
        ;

    if (count == 1)
    {
        /* no entries found, so just fail here
         */
        return -1;
    }
    *results = calloc(count, sizeof(struct flux_entry));
    if (!*results)
    {
        return -1;
    }
//   memset(*results, 0, sizeof(struct flux_entry) * count);
    // init GeoIP //
    gi = GeoIP_new(GEOIP_STANDARD);
    for (isflux = 0, cur = res; cur; cur = cur ->ai_next, ++isflux)
    {
        int size;

        switch (cur->ai_family)
        {
            case AF_INET:
                addr_ptr = &((struct sockaddr_in *) cur->ai_addr)->sin_addr;
                size = sizeof ("xxx.xxx.xxx.xxx");
                break;
            case AF_INET6:
                addr_ptr = &((struct sockaddr_in6 *) cur->ai_addr)->sin6_addr;
                size = sizeof ("xx:xx:xx:xx:xx:xx:xx:xx");
                break;
            default:
                continue;
        }
        addr_str = malloc(size);
        if (!addr_str) continue;

        inet_ntop (cur->ai_family, addr_ptr, addr_str, size);
        (*results)[isflux].addr_str = addr_str;

        if((GeoIP_country_code_by_name(gi, addr_str)) == NULL)
        {
            break;
        }
        else
        {
            memcpy(  &(*results)[isflux].cc,
                     GeoIP_country_code_by_name(gi, addr_str), 
                     sizeof (**results).cc);
        }
    }

    (*results)[isflux].addr_str = NULL;
    (*results)[isflux].cc[0] = 0;
    (*results)[isflux].cc[1] = 0;

    GeoIP_delete(gi);

    return isflux;
}
예제 #23
0
gint
main (gint argc, gchar **argv)
{
    GeoIP *geoip;
    const gchar *remote_addr;
    const gchar *path_info;
    gchar **path_parts;
    const gchar *country;
    gchar *action;
    gchar *input;
    gchar *domain;
    gchar *affiliate_code;
    gchar *p;
    gchar *dest_url = NULL;
    gboolean direct_url = FALSE;

    country = NULL;
    input = NULL;
    action = NULL;

    remote_addr = g_getenv ("REMOTE_ADDR");

    path_parts = g_strsplit (path_info = g_getenv ("PATH_INFO"), "/", 4);
    if (path_parts != NULL &&
        path_parts[0] != NULL &&
        (country = path_parts[1]) != NULL &&
        (action = path_parts[2]) != NULL) {
        input = path_parts[3];
    }

    if ((p = strrchr (remote_addr, ':')) != NULL) {
        remote_addr = p + 1;
    }

    if (country == NULL || strcmp (country, "geo") == 0) {
        geoip = GeoIP_new (GEOIP_STANDARD);
        country = GeoIP_country_code_by_name (geoip, remote_addr);
    }

    // We ask that no one change these affiliate codes. ALL (100%) revenue
    // generated by these affiliate IDs is sent directly to the GNOME
    // Foundation. The GNOME Foundation controls/owns these affiliate IDs.
    // Please help support Free Software through the GNOME Foundation!
    if (country == NULL || strcmp (country, "US") == 0) {
        domain = "com";
        affiliate_code = "banshee-20";
    } else if (strcmp (country, "FR") == 0) {
        domain = "fr";
        affiliate_code = "banshee-fr-21";
    } else if (strcmp (country, "UK") == 0) {
        domain = "co.uk";
        affiliate_code = "banshee-uk-21";
    } else if (strcmp (country, "DE") == 0 ||
        strcmp (country, "CH") == 0 ||
        strcmp (country, "AT") == 0) {
        domain = "de";
        affiliate_code = "banshee-de-21";
    } else if (strcmp (country, "JP") == 0) {
        domain = "co.jp";
        affiliate_code = "banshee-jp-22";
    } else {
        domain = "com";
        affiliate_code = "banshee-20";
    }

    if (strcmp (action, "search") == 0) {
        dest_url = g_strdup_printf ("http://www.amazon.%s/s/ref=nb_sb_noss?url=search-alias%%3Ddigital-music&field-keywords=%s", domain, input);
    } else if (strcmp (action, "sign_out") == 0) {
        dest_url = g_strdup_printf ("http://www.amazon.%s/gp/help/customer/sign-out.html/ref=ya__lo?ie=UTF8&returnPath=%%2Fmp3", domain);
    } else if (strcmp (action, "about") == 0) {
        dest_url = g_strdup ("http://banshee.fm/about/revenue/");
        direct_url = TRUE;
    }

    if (dest_url == NULL) {
        dest_url = g_strdup_printf ("http://www.amazon.%s/mp3/", domain);
    }

    if (direct_url) {
        printf ("Location: %s" "\n\n", dest_url);
    } else {
        printf ("Location: http://www.amazon.%s/gp/redirect.html?ie=UTF8&location=%s&tag=%s" "\n\n",
            domain,
            g_uri_escape_string (dest_url, NULL, TRUE),
            affiliate_code
        );
    }

    return 0;
}
예제 #24
0
static int 
geoip_header_parser(request_rec * r)
{
	char           *orgorisp;
	char           *ipaddr;
	short int       country_id;
	GeoIP          *gip;
	const char     *continent_code;
	const char     *country_code;
	const char     *country_name;
	const char     *region_name;

	geoip_server_config_rec *cfg;

	unsigned char   databaseType;
	GeoIPRecord    *gir;
	GeoIPRegion    *giregion;
	int             i;
	int             netspeed;
	/* For splitting proxy headers */
	char           *ipaddr_ptr = 0;
	char           *comma_ptr;
	char           *found_ip;
	apr_sockaddr_t *sa;
	char           *hostname = 0;

	cfg = ap_get_module_config(r->server->module_config, &geoip_module);

	if (!cfg)
		return DECLINED;

	if (!cfg->scanProxyHeaders) {
		ipaddr = r->connection->remote_ip;
	}
	else {
		ap_add_common_vars(r);
		if (apr_table_get(r->subprocess_env, "HTTP_CLIENT_IP")) {
			ipaddr_ptr = (char *) apr_table_get(r->subprocess_env, "HTTP_CLIENT_IP");
		}
		else if (apr_table_get(r->subprocess_env, "HTTP_X_FORWARDED_FOR")) {
			ipaddr_ptr = (char *) apr_table_get(r->subprocess_env, "HTTP_X_FORWARDED_FOR");
		}
		else if (apr_table_get(r->headers_in, "X-Forwarded-For")) {
			ipaddr_ptr = (char *) apr_table_get(r->headers_in, "X-Forwarded-For");
		}
		else if (apr_table_get(r->subprocess_env, "HTTP_REMOTE_ADDR")) {
			ipaddr_ptr = (char *) apr_table_get(r->subprocess_env, "HTTP_REMOTE_ADDR");
		}
		if (!ipaddr_ptr) {
			ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r->server, "[mod_geoip]: Error while getting ipaddr from proxy headers. Using REMOTE_ADDR.");
			ipaddr = r->connection->remote_ip;
		}
		else {
			ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r->server, "[mod_geoip]: IPADDR_PTR: %s", ipaddr_ptr);

			if (cfg->use_left_public_x_forwarded_for_ip) {
				// find the first public IP address in a potentially comma-separated list,
				// fall back to remote_ip if we can't find one
				ipaddr = first_public_ip_in_list(ipaddr_ptr, r->connection->remote_ip);
			} else {
				// leaving some of the following inconsistent indenting intact for easier diff to original maxmind src

                       /*
                        * Check to ensure that the HTTP_CLIENT_IP or
                        * X-Forwarded-For header is not a comma separated
                        * list of addresses, which would cause mod_geoip to
                        * return no country code. If the header is a comma
                        * separated list, return the first IP address in the
                        * list, which is (hopefully!) the real client IP.
                        */
                        ipaddr = (char *) calloc(8*4+7+1, sizeof(char));

                        if (cfg->use_last_x_forwarded_for_ip ){
                                comma_ptr = strrchr(ipaddr_ptr, ',');
                                if ( comma_ptr ) {
                                        /* skip over whitespace */
                                        ipaddr_ptr = comma_ptr + strspn(comma_ptr, ", \t");
                                }
                        }

                        strncpy(ipaddr, ipaddr_ptr, 8*4+7);
                        comma_ptr = strchr(ipaddr, ',');
                        if (comma_ptr != 0)
                                *comma_ptr = '\0';
			}
 		}
	}

/* this block should be removed! */
#if 1
	if (!cfg->gips) {
		if (cfg->GeoIPFilenames != NULL) {
			cfg->gips = malloc(sizeof(GeoIP *) * cfg->numGeoIPFiles);
			for (i = 0; i < cfg->numGeoIPFiles; i++) {
				cfg->gips[i] = GeoIP_open(cfg->GeoIPFilenames[i], (cfg->GeoIPFlags2[i] == GEOIP_UNKNOWN) ? cfg->GeoIPFlags : cfg->GeoIPFlags2[i]);

				if (cfg->gips[i]) {
					if (cfg->GeoIPEnableUTF8) {
						GeoIP_set_charset(cfg->gips[i], GEOIP_CHARSET_UTF8);
					}
				}
				else {
					ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, "[mod_geoip]: Error while opening data file %s", cfg->GeoIPFilenames[i]);
					return DECLINED;
				}
			}
		}
		else {
			cfg->gips = malloc(sizeof(GeoIP *));
			cfg->gips[0] = GeoIP_new(GEOIP_STANDARD);
			if (!cfg->gips[0]) {
				ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, "[mod_geoip]: Error while opening data file");
				return DECLINED;
			}
			cfg->numGeoIPFiles = 1;
		}
	}
#endif

	if (cfg->GeoIPEnableHostnameLookups
			&& apr_sockaddr_info_get(&sa, ipaddr, APR_INET, 0, 0, r->pool) == APR_SUCCESS
			&& apr_getnameinfo(&hostname, sa, 0) == APR_SUCCESS) {
		ap_str_tolower(hostname);
	}

	if (!hostname)
		hostname = ipaddr;

	if (cfg->GeoIPOutput & GEOIP_NOTES) {
		apr_table_setn(r->notes, "GEOIP_ADDR", ipaddr);
		apr_table_setn(r->notes, "GEOIP_HOST", hostname);
	}
	if (cfg->GeoIPOutput & GEOIP_ENV) {
		apr_table_setn(r->subprocess_env, "GEOIP_ADDR", ipaddr);
		apr_table_setn(r->subprocess_env, "GEOIP_HOST", hostname);
	}

	for (i = 0; i < cfg->numGeoIPFiles; i++) {

		/*
		 * skip database handles that can not be opned for some
		 * reason
		 */
		if (cfg->gips[i] == NULL)
			continue;

		databaseType = cfg->gips[i] ? GeoIP_database_edition(cfg->gips[i]) : -1;	/* -1 is "magic value"
												 * in case file not
												 * found */
		switch (databaseType) {
                case GEOIP_NETSPEED_EDITION_REV1:
                  orgorisp = GeoIP_name_by_addr(cfg->gips[i], ipaddr);
                  if (orgorisp != NULL) {
   	            if (cfg->GeoIPOutput & GEOIP_NOTES) {
	              apr_table_setn(r->notes, "GEOIP_NETSPEED", orgorisp);
	            }
	            if (cfg->GeoIPOutput & GEOIP_ENV) {
	              apr_table_setn(r->subprocess_env, "GEOIP_NETSPEED", orgorisp);
	            }
                  }
                break;
 
		case GEOIP_NETSPEED_EDITION:
			netspeed = GeoIP_id_by_addr(cfg->gips[i], ipaddr);
			if (netspeed == GEOIP_UNKNOWN_SPEED) {
				netspeedstring = "unknown";
			}
			else if (netspeed == GEOIP_DIALUP_SPEED) {
				netspeedstring = "dialup";
			}
			else if (netspeed == GEOIP_CABLEDSL_SPEED) {
				netspeedstring = "cabledsl";
			}
			else if (netspeed == GEOIP_CORPORATE_SPEED) {
				netspeedstring = "corporate";
			}
			if (cfg->GeoIPOutput & GEOIP_NOTES) {
				apr_table_setn(r->notes, "GEOIP_NETSPEED", netspeedstring);
			}
			if (cfg->GeoIPOutput & GEOIP_ENV) {
				apr_table_setn(r->subprocess_env, "GEOIP_NETSPEED", netspeedstring);
			}
			break;
		case GEOIP_COUNTRY_EDITION_V6:
			/* Get the Country ID */
			country_id = GeoIP_country_id_by_addr_v6(cfg->gips[i], ipaddr);

      if ( country_id > 0 ) {
			  /* Lookup the Code and the Name with the ID */
			  continent_code = GeoIP_country_continent[country_id];
			  country_code = GeoIP_country_code[country_id];
			  country_name = GeoIP_country_name[country_id];

			  if (cfg->numGeoIPFiles == 0) {
				  cfg->numGeoIPFiles = 0;
			  }
			  if (cfg->GeoIPFilenames == 0) {
				  cfg->GeoIPFilenames = 0;
			  }
			  /* Set it for our user */
			  if (cfg->GeoIPOutput & GEOIP_NOTES) {
				  apr_table_setn(r->notes, "GEOIP_CONTINENT_CODE_V6", continent_code);
		  		apr_table_setn(r->notes, "GEOIP_COUNTRY_CODE_V6", country_code);
			  	apr_table_setn(r->notes, "GEOIP_COUNTRY_NAME_V6", country_name);
			  }
			  if (cfg->GeoIPOutput & GEOIP_ENV) {
				  apr_table_setn(r->subprocess_env, "GEOIP_CONTINENT_CODE_V6", continent_code);
				  apr_table_setn(r->subprocess_env, "GEOIP_COUNTRY_CODE_V6", country_code);
				  apr_table_setn(r->subprocess_env, "GEOIP_COUNTRY_NAME_V6", country_name);
			  }
			}
			break;
		case GEOIP_COUNTRY_EDITION:
			/* Get the Country ID */
			country_id = GeoIP_country_id_by_addr(cfg->gips[i], ipaddr);

      if ( country_id > 0 ) {
			  /* Lookup the Code and the Name with the ID */
			  continent_code = GeoIP_country_continent[country_id];
			  country_code = GeoIP_country_code[country_id];
			  country_name = GeoIP_country_name[country_id];

			  if (cfg->numGeoIPFiles == 0) {
				  cfg->numGeoIPFiles = 0;
			  }
			  if (cfg->GeoIPFilenames == 0) {
				  cfg->GeoIPFilenames = 0;
			  }
			  /* Set it for our user */
			  if (cfg->GeoIPOutput & GEOIP_NOTES) {
				  apr_table_setn(r->notes, "GEOIP_CONTINENT_CODE", continent_code);
		  		apr_table_setn(r->notes, "GEOIP_COUNTRY_CODE", country_code);
			  	apr_table_setn(r->notes, "GEOIP_COUNTRY_NAME", country_name);
			  }
			  if (cfg->GeoIPOutput & GEOIP_ENV) {
				  apr_table_setn(r->subprocess_env, "GEOIP_CONTINENT_CODE", continent_code);
				  apr_table_setn(r->subprocess_env, "GEOIP_COUNTRY_CODE", country_code);
				  apr_table_setn(r->subprocess_env, "GEOIP_COUNTRY_NAME", country_name);
			  }
			}
			break;
		case GEOIP_REGION_EDITION_REV0:
		case GEOIP_REGION_EDITION_REV1:
			giregion = GeoIP_region_by_name(cfg->gips[i], ipaddr);
			if (giregion != NULL) {
			  if ( giregion->country_code[0] ) {
			    region_name = GeoIP_region_name_by_code(giregion->country_code, giregion->region);
			  }
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					if ( giregion->country_code[0] ){
						apr_table_set(r->notes, "GEOIP_COUNTRY_CODE", giregion->country_code);
					}
					if (giregion->region[0]) {
						apr_table_set(r->notes, "GEOIP_REGION", giregion->region);
					}
					if ( region_name != NULL ){
					  apr_table_set(r->notes, "GEOIP_REGION_NAME", region_name);
					}
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					if ( giregion->country_code[0] ){
						apr_table_set(r->subprocess_env, "GEOIP_COUNTRY_CODE", giregion->country_code);
					}
					if (giregion->region[0]) {
					      apr_table_set(r->subprocess_env, "GEOIP_REGION", giregion->region);
					}
					if ( region_name != NULL ){
					  apr_table_set(r->subprocess_env, "GEOIP_REGION_NAME", region_name);
					}
				}
				GeoIPRegion_delete(giregion);
			}
			break;
		case GEOIP_CITY_EDITION_REV0_V6:
		case GEOIP_CITY_EDITION_REV1_V6:
			gir = GeoIP_record_by_addr_v6(cfg->gips[i], ipaddr);
			if (gir != NULL) {
			        if ( gir->country_code != NULL ) {
				  region_name = GeoIP_region_name_by_code(gir->country_code, gir->region);
				}
				sprintf(metrocodestr, "%d", gir->dma_code);
				sprintf(areacodestr, "%d", gir->area_code);
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_CONTINENT_CODE_V6", gir->continent_code);
					apr_table_setn(r->notes, "GEOIP_COUNTRY_CODE_V6", gir->country_code);
					apr_table_setn(r->notes, "GEOIP_COUNTRY_NAME_V6", gir->country_name);
					if (gir->region != NULL) {
						apr_table_set(r->notes, "GEOIP_REGION_V6", gir->region);
						if ( region_name != NULL ){
						  apr_table_set(r->notes, "GEOIP_REGION_NAME_V6", region_name);
						}
					}
					if (gir->city != NULL) {
						apr_table_set(r->notes, "GEOIP_CITY_V6", gir->city);
					}
					apr_table_setn(r->notes, "GEOIP_DMA_CODE_V6", metrocodestr);
					apr_table_setn(r->notes, "GEOIP_METRO_CODE_V6", metrocodestr);
					apr_table_setn(r->notes, "GEOIP_AREA_CODE_V6", areacodestr);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_CONTINENT_CODE_V6", gir->continent_code);
					apr_table_setn(r->subprocess_env, "GEOIP_COUNTRY_CODE_V6", gir->country_code);
					apr_table_setn(r->subprocess_env, "GEOIP_COUNTRY_NAME_V6", gir->country_name);
					if (gir->region != NULL) {
						apr_table_set(r->subprocess_env, "GEOIP_REGION_V6", gir->region);
						if ( region_name != NULL ){
						  apr_table_set(r->subprocess_env, "GEOIP_REGION_NAME_V6", region_name);
						}
					}
					if (gir->city != NULL) {
						apr_table_set(r->subprocess_env, "GEOIP_CITY_V6", gir->city);
					}
					apr_table_setn(r->subprocess_env, "GEOIP_DMA_CODE_V6", metrocodestr);
					apr_table_setn(r->subprocess_env, "GEOIP_METRO_CODE_V6", metrocodestr);
					apr_table_setn(r->subprocess_env, "GEOIP_AREA_CODE_V6", areacodestr);
				}
				sprintf(latstr, "%f", gir->latitude);
				sprintf(lonstr, "%f", gir->longitude);
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_LATITUDE_V6", latstr);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_LATITUDE_V6", latstr);
				}
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_LONGITUDE_V6", lonstr);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_LONGITUDE_V6", lonstr);
				}
				if (gir->postal_code != NULL) {
					if (cfg->GeoIPOutput & GEOIP_NOTES) {
						apr_table_set(r->notes, "GEOIP_POSTAL_CODE_V6", gir->postal_code);
					}
					if (cfg->GeoIPOutput & GEOIP_ENV) {
						apr_table_set(r->subprocess_env, "GEOIP_POSTAL_CODE_V6", gir->postal_code);
					}
				}
				GeoIPRecord_delete(gir);
			}
			break;
		case GEOIP_CITY_EDITION_REV0:
		case GEOIP_CITY_EDITION_REV1:
			gir = GeoIP_record_by_addr(cfg->gips[i], ipaddr);
			if (gir != NULL) {
			        if ( gir->country_code != NULL ) {
				  region_name = GeoIP_region_name_by_code(gir->country_code, gir->region);
				}
				sprintf(metrocodestr, "%d", gir->dma_code);
				sprintf(areacodestr, "%d", gir->area_code);
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_CONTINENT_CODE", gir->continent_code);
					apr_table_setn(r->notes, "GEOIP_COUNTRY_CODE", gir->country_code);
					apr_table_setn(r->notes, "GEOIP_COUNTRY_NAME", gir->country_name);
					if (gir->region != NULL) {
						apr_table_set(r->notes, "GEOIP_REGION", gir->region);
						if ( region_name != NULL ){
						  apr_table_set(r->notes, "GEOIP_REGION_NAME", region_name);
						}
					}
					if (gir->city != NULL) {
						apr_table_set(r->notes, "GEOIP_CITY", gir->city);
					}
					apr_table_setn(r->notes, "GEOIP_DMA_CODE", metrocodestr);
					apr_table_setn(r->notes, "GEOIP_METRO_CODE", metrocodestr);
					apr_table_setn(r->notes, "GEOIP_AREA_CODE", areacodestr);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_CONTINENT_CODE", gir->continent_code);
					apr_table_setn(r->subprocess_env, "GEOIP_COUNTRY_CODE", gir->country_code);
					apr_table_setn(r->subprocess_env, "GEOIP_COUNTRY_NAME", gir->country_name);
					if (gir->region != NULL) {
						apr_table_set(r->subprocess_env, "GEOIP_REGION", gir->region);
						if ( region_name != NULL ){
						  apr_table_set(r->subprocess_env, "GEOIP_REGION_NAME", region_name);
						}
					}
					if (gir->city != NULL) {
						apr_table_set(r->subprocess_env, "GEOIP_CITY", gir->city);
					}
					apr_table_setn(r->subprocess_env, "GEOIP_DMA_CODE", metrocodestr);
					apr_table_setn(r->subprocess_env, "GEOIP_METRO_CODE", metrocodestr);
					apr_table_setn(r->subprocess_env, "GEOIP_AREA_CODE", areacodestr);
				}
				sprintf(latstr, "%f", gir->latitude);
				sprintf(lonstr, "%f", gir->longitude);
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_LATITUDE", latstr);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_LATITUDE", latstr);
				}
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_LONGITUDE", lonstr);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_LONGITUDE", lonstr);
				}
				if (gir->postal_code != NULL) {
					if (cfg->GeoIPOutput & GEOIP_NOTES) {
						apr_table_set(r->notes, "GEOIP_POSTAL_CODE", gir->postal_code);
					}
					if (cfg->GeoIPOutput & GEOIP_ENV) {
						apr_table_set(r->subprocess_env, "GEOIP_POSTAL_CODE", gir->postal_code);
					}
				}
				GeoIPRecord_delete(gir);
			}
			break;
		case GEOIP_ORG_EDITION:
			orgorisp = GeoIP_name_by_addr(cfg->gips[i], ipaddr);
			if (orgorisp != NULL) {
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_ORGANIZATION", orgorisp);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_ORGANIZATION", orgorisp);
				}
			}
			break;
		case GEOIP_ISP_EDITION:
			orgorisp = GeoIP_name_by_addr(cfg->gips[i], ipaddr);
			if (orgorisp != NULL) {
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_ISP", orgorisp);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_ISP", orgorisp);
				}
			}
			break;
		case GEOIP_DOMAIN_EDITION:
			orgorisp = GeoIP_name_by_addr(cfg->gips[i], ipaddr);
			if (orgorisp != NULL) {
				if (cfg->GeoIPOutput & GEOIP_NOTES) {
					apr_table_setn(r->notes, "GEOIP_DOMAIN", orgorisp);
				}
				if (cfg->GeoIPOutput & GEOIP_ENV) {
					apr_table_setn(r->subprocess_env, "GEOIP_DOMAIN", orgorisp);
				}
			}
			break;
		}
	}

	return OK;
}
예제 #25
0
int
main(int argc, char *argv[])
{
  /* Check to see if the user is running us as root, which is a nono */
  if (!geteuid())
  {
    fprintf(stderr, "ERROR: This server won't run as root/superuser\n");
    return -1;
  }

  /* Setup corefile size immediately after boot -kre */
  setup_corefile();

  /* Save server boot time right away, so getrusage works correctly */
  set_time();

  /* It's not random, but it ought to be a little harder to guess */
  init_genrand(SystemTime.tv_sec ^ (SystemTime.tv_usec | (getpid() << 20)));

  dlinkAdd(&me, &me.node, &global_client_list);

  ConfigGeneral.dpath      = DPATH;
  ConfigGeneral.spath      = SPATH;
  ConfigGeneral.mpath      = MPATH;
  ConfigGeneral.configfile = CPATH;    /* Server configuration file */
  ConfigGeneral.klinefile  = KPATH;    /* Server kline file         */
  ConfigGeneral.glinefile  = GPATH;    /* Server gline file         */
  ConfigGeneral.xlinefile  = XPATH;    /* Server xline file         */
  ConfigGeneral.dlinefile  = DLPATH;   /* dline file                */
  ConfigGeneral.resvfile   = RESVPATH; /* resv file                 */

  myargv = argv;
  umask(077);  /* umask 077: u=rwx,g=,o= */

  parseargs(&argc, &argv, myopts);

  if (printVersion)
  {
    printf("ircd: version %s(%s)\n", ircd_version, serno);
    exit(EXIT_SUCCESS);
  }

  if (chdir(ConfigGeneral.dpath))
  {
    perror("chdir");
    exit(EXIT_FAILURE);
  }

  ssl_init();

  if (!server_state.foreground)
  {
    make_daemon();
    close_standard_fds(); /* this needs to be before init_netio()! */
  }
  else
    print_startup(getpid());

  setup_signals();

  /* We need this to initialise the fd array before anything else */
  fdlist_init();
  log_set_file(LOG_TYPE_IRCD, 0, logFileName);

  init_netio();         /* This needs to be setup early ! -- adrian */

  /* Check if there is pidfile and daemon already running */
  check_pidfile(pidFileName);

  mp_pool_init();
  init_dlink_nodes();
  init_isupport();
  dbuf_init();
  hash_init();
  ipcache_init();
  client_init();
  class_init();
  whowas_init();
  watch_init();
  auth_init();          /* Initialise the auth code */
  init_resolver();      /* Needs to be setup before the io loop */
  modules_init();
  read_conf_files(1);   /* cold start init conf files */
  init_uid();
  initialize_server_capabs();   /* Set up default_server_capabs */
  initialize_global_set_options();  /* Has to be called after read_conf_files() */
  channel_init();
  read_links_file();
  motd_init();
  user_usermodes_init();
#ifdef HAVE_LIBGEOIP
  geoip_ctx = GeoIP_new(GEOIP_MEMORY_CACHE);
#endif

  if (EmptyString(ConfigServerInfo.sid))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server id specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.id, ConfigServerInfo.sid, sizeof(me.id));

  if (EmptyString(ConfigServerInfo.name))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server name specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.name, ConfigServerInfo.name, sizeof(me.name));

  /* serverinfo{} description must exist.  If not, error out.*/
  if (EmptyString(ConfigServerInfo.description))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server description specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.info, ConfigServerInfo.description, sizeof(me.info));

  me.from = &me;
  me.servptr = &me;
  me.connection->lasttime = CurrentTime;
  me.connection->since = CurrentTime;
  me.connection->firsttime = CurrentTime;

  SetMe(&me);
  make_server(&me);

  hash_add_id(&me);
  hash_add_client(&me);

  dlinkAdd(&me, make_dlink_node(), &global_server_list);

  load_kline_database();
  load_dline_database();
  load_gline_database();
  load_xline_database();
  load_resv_database();

  load_all_modules(1);
  load_conf_modules();
  load_core_modules(1);

  write_pidfile(pidFileName);

  ilog(LOG_TYPE_IRCD, "Server Ready");

  event_addish(&event_cleanup_glines, NULL);
  event_addish(&event_cleanup_tklines, NULL);

  /* We want try_connections to be called as soon as possible now! -- adrian */
  /* No, 'cause after a restart it would cause all sorts of nick collides */
  event_addish(&event_try_connections, NULL);

  /* Setup the timeout check. I'll shift it later :)  -- adrian */
  event_add(&event_comm_checktimeouts, NULL);

  event_addish(&event_save_all_databases, NULL);

  if (ConfigServerHide.links_delay > 0)
  {
    event_write_links_file.when = ConfigServerHide.links_delay;
    event_addish(&event_write_links_file, NULL);
  }
  else
    ConfigServerHide.links_disabled = 1;

  if (splitmode)
    event_addish(&splitmode_event, NULL);

  io_loop();
  return 0;
}
예제 #26
0
int
main(int argc, char **argv)
{
   Eina_File *f;
   Eina_Iterator *it;
   Eina_File_Line *l;
   GeoIP *geo;
   Community_Country *country;
   unsigned long long correct = 0;
   unsigned long long lines = 0;
   int i;

   if (argc != 2) return -1;

   eina_init();

   community = eina_hash_stringshared_new(NULL);
   days = eina_hash_new(_community_day_key_length,
                             _community_day_key_cmp,
                             _community_day_key_hash,
                             NULL, 5);
   countries = eina_hash_string_superfast_new(NULL);
   geo = GeoIP_new(GEOIP_STANDARD);
   memset(months, 0, sizeof (months));

   /* Read real name country to tld file */
   f = eina_file_open("country_tld.csv", EINA_FALSE);
   if (!f) return -1;

   it = eina_file_map_lines(f);
   EINA_ITERATOR_FOREACH(it, l)
     {
        const char *s;
        int i;

        s = memchr(l->start, ',', l->length);
        if (!s) continue ;

        country = calloc(1, sizeof (Community_Country));
        country->tld = _eina_stringshare_up(l->start, s - l->start);
        country->country = _eina_stringshare_up(s + 1, l->length - (s - l->start + 1));
        country->access = eina_hash_stringshared_new(NULL);

        eina_hash_direct_add(countries, country->tld, country);
     }
   eina_iterator_free(it);
   eina_file_close(f);

   /* Read population information */
   f = eina_file_open("country_population.csv", EINA_FALSE);
   if (!f) return -1;

   it = eina_file_map_lines(f);
   EINA_ITERATOR_FOREACH(it, l)
     {
        Eina_Iterator *it2;
        const char *s;
        const char *country_name;
        const char *r;

        for (s = l->start; s < l->end; s++)
          {
             const char *convert = VIGRID_NUMBER_SEARCH;

             r = strchr(convert, *s);
             if (r) break ;
          }

        if (!r) continue;

        country = NULL;
        country_name = _eina_stringshare_up(l->start, s - l->start - 1);

        it2 = eina_hash_iterator_data_new(countries);
        EINA_ITERATOR_FOREACH(it2, country)
          {
             if (country->country == country_name)
               {
                  unsigned long long offset = s - l->start;

                  country->population = _eina_file_int_get(l, &offset);
                  break;
               }
          }
        eina_iterator_free(it2);
     }
예제 #27
0
static int geoip_header_parser(request_rec * r)
{
    char *orgorisp;
    char *ipaddr;
    char *free_me = NULL;
    short int country_id;
    const char *continent_code;
    const char *country_code;
    const char *country_name;
    const char *region_name;

    geoip_server_config_rec *cfg;

    unsigned char databaseType;
    GeoIPRecord *gir;
    GeoIPRegion *giregion;
    int i;
    int netspeed;
    /* For splitting proxy headers */
    char *ipaddr_ptr = NULL;
    char *comma_ptr;
    cfg = ap_get_module_config(r->server->module_config, &geoip_module);

    if (!cfg)
        return DECLINED;

    if (!cfg->scanProxyHeaders) {
        ipaddr = _get_client_ip(r);
    } else {
        ap_add_common_vars(r);
        if (apr_table_get(r->subprocess_env, "HTTP_CLIENT_IP")) {
            ipaddr_ptr =
                (char *)apr_table_get(r->subprocess_env, "HTTP_CLIENT_IP");
        } else if (apr_table_get(r->subprocess_env, "HTTP_X_FORWARDED_FOR")) {
            ipaddr_ptr =
                (char *)apr_table_get(r->subprocess_env,
                                      "HTTP_X_FORWARDED_FOR");
        } else if (apr_table_get(r->headers_in, "X-Forwarded-For")) {
            ipaddr_ptr =
                (char *)apr_table_get(r->headers_in, "X-Forwarded-For");
        } else if (apr_table_get(r->subprocess_env, "HTTP_REMOTE_ADDR")) {
            ipaddr_ptr =
                (char *)apr_table_get(r->subprocess_env, "HTTP_REMOTE_ADDR");
        }
        if (!ipaddr_ptr) {
            ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0,
                         r->server,
                         "[mod_geoip]: Error while getting ipaddr from proxy headers. Using REMOTE_ADDR.");
            ipaddr = _get_client_ip(r);
        } else {
            /* Found XFF like header */
            ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0,
                         r->server, "[mod_geoip]: IPADDR_PTR: %s", ipaddr_ptr);

            if (cfg->proxyHeaderMode ==
                GEOIP_PROXY_HEADER_MODE_FIRST_NON_PRIVATE_IP) {
                ipaddr = free_me = _get_ip_from_xff(ipaddr_ptr);
                if (!ipaddr)
                    ipaddr = _get_client_ip(r);
            } else {
                ipaddr = free_me = (char *)calloc(8 * 4 + 7 + 1, sizeof(char));
                /* proxyHeaderMode is
                 * GEOIP_PROXY_HEADER_MODE_LAST_IP or GEOIP_PROXY_HEADER_MODE_FIRST_IP
                 */

                /*
                 * Check to ensure that the HTTP_CLIENT_IP or
                 * X-Forwarded-For header is not a comma separated
                 * list of addresses, which would cause mod_geoip to
                 * return no country code. If the header is a comma
                 * separated list, return the first IP address in the
                 * list, which is (hopefully!) the real client IP.
                 */

                if (cfg->proxyHeaderMode == GEOIP_PROXY_HEADER_MODE_LAST_IP) {
                    comma_ptr = strrchr(ipaddr_ptr, ',');
                    if (comma_ptr) {
                        /* skip over whitespace */
                        ipaddr_ptr = comma_ptr + strspn(comma_ptr, ", \t");
                    }
                }

                strncpy(ipaddr, ipaddr_ptr, 8 * 4 + 7);
                comma_ptr = strchr(ipaddr, ',');
                if (comma_ptr != 0)
                    *comma_ptr = '\0';
            }
        }
    }

/* this block should be removed! */
#if 1
    if (!cfg->gips) {
        if (cfg->GeoIPFilenames != NULL) {
            cfg->gips = malloc(sizeof(GeoIP *) * cfg->numGeoIPFiles);
            for (i = 0; i < cfg->numGeoIPFiles; i++) {
                cfg->gips[i] =
                    GeoIP_open(cfg->GeoIPFilenames[i],
                               (cfg->GeoIPFlags2[i] ==
                                GEOIP_UNKNOWN) ? cfg->GeoIPFlags
                               : cfg->GeoIPFlags2[i]);

                if (cfg->gips[i]) {
                    if (cfg->GeoIPEnableUTF8) {
                        GeoIP_set_charset(cfg->gips[i], GEOIP_CHARSET_UTF8);
                    }
                } else {
                    ap_log_error(APLOG_MARK, APLOG_ERR, 0,
                                 r->server,
                                 "[mod_geoip]: Error while opening data file %s",
                                 cfg->GeoIPFilenames[i]);
                    return DECLINED;
                }
            }
        } else {
            cfg->gips = malloc(sizeof(GeoIP *));
            cfg->gips[0] = GeoIP_new(GEOIP_STANDARD);
            if (!cfg->gips[0]) {
                ap_log_error(APLOG_MARK, APLOG_ERR, 0,
                             r->server,
                             "[mod_geoip]: Error while opening data file");
                return DECLINED;
            }
            cfg->numGeoIPFiles = 1;
        }
    }
#endif

    set_geoip_output(cfg, r, "GEOIP_ADDR", ipaddr);

    for (i = 0; i < cfg->numGeoIPFiles; i++) {

        /*
         * skip database handles that can not be opned for some
         * reason
         */
        if (cfg->gips[i] == NULL)
            continue;

        databaseType = cfg->gips[i] ? GeoIP_database_edition(cfg->gips[i]) : -1;        /* -1 is "magic value"
                                                                                         * in case file not
                                                                                         * found */
        switch (databaseType) {
        case GEOIP_NETSPEED_EDITION_REV1:
            orgorisp = GeoIP_name_by_addr(cfg->gips[i], ipaddr);
            setn_geoip_output(cfg, r, "GEOIP_NETSPEED", orgorisp);
            break;

        case GEOIP_NETSPEED_EDITION:
            netspeed = GeoIP_id_by_addr(cfg->gips[i], ipaddr);
            if (netspeed == GEOIP_UNKNOWN_SPEED) {
                netspeedstring = "unknown";
            } else if (netspeed == GEOIP_DIALUP_SPEED) {
                netspeedstring = "dialup";
            } else if (netspeed == GEOIP_CABLEDSL_SPEED) {
                netspeedstring = "cabledsl";
            } else if (netspeed == GEOIP_CORPORATE_SPEED) {
                netspeedstring = "corporate";
            }
            setn_geoip_output(cfg, r, "GEOIP_NETSPEED", netspeedstring);
            break;
        case GEOIP_COUNTRY_EDITION_V6:
            /* Get the Country ID */
            country_id = GeoIP_id_by_addr_v6(cfg->gips[i], ipaddr);

            if (country_id > 0) {
                /* Lookup the Code and the Name with the ID */
                continent_code = GeoIP_country_continent[country_id];
                country_code = GeoIP_country_code[country_id];
                country_name = GeoIP_country_name[country_id];

                if (cfg->numGeoIPFiles == 0) {
                    cfg->numGeoIPFiles = 0;
                }
                if (cfg->GeoIPFilenames == 0) {
                    cfg->GeoIPFilenames = 0;
                }
                /* Set it for our user */
                setn_geoip_output(cfg, r, "GEOIP_CONTINENT_CODE_V6",
                                  continent_code);
                setn_geoip_output(cfg, r, "GEOIP_COUNTRY_CODE_V6",
                                  country_code);
                setn_geoip_output(cfg, r, "GEOIP_COUNTRY_NAME_V6",
                                  country_name);
            }
            break;
        case GEOIP_COUNTRY_EDITION:
            /* Get the Country ID */
            country_id = GeoIP_country_id_by_addr(cfg->gips[i], ipaddr);

            if (country_id > 0) {
                /* Lookup the Code and the Name with the ID */
                continent_code = GeoIP_country_continent[country_id];
                country_code = GeoIP_country_code[country_id];
                country_name = GeoIP_country_name[country_id];

                if (cfg->numGeoIPFiles == 0) {
                    cfg->numGeoIPFiles = 0;
                }
                if (cfg->GeoIPFilenames == 0) {
                    cfg->GeoIPFilenames = 0;
                }
                /* Set it for our user */
                setn_geoip_output(cfg, r, "GEOIP_CONTINENT_CODE",
                                  continent_code);
                setn_geoip_output(cfg, r, "GEOIP_COUNTRY_CODE", country_code);
                setn_geoip_output(cfg, r, "GEOIP_COUNTRY_NAME", country_name);
            }

            break;
        case GEOIP_REGION_EDITION_REV0:
        case GEOIP_REGION_EDITION_REV1:
            giregion = GeoIP_region_by_name(cfg->gips[i], ipaddr);
            if (giregion != NULL) {
                region_name = NULL;
                if (giregion->country_code[0]) {
                    region_name =
                        GeoIP_region_name_by_code
                        (giregion->country_code, giregion->region);
                    set_geoip_output(cfg, r, "GEOIP_COUNTRY_CODE",
                                      giregion->country_code);
                    country_id = GeoIP_id_by_code(giregion->country_code);
                    setn_geoip_output(cfg, r, "GEOIP_COUNTRY_NAME",
                                      GeoIP_country_name[country_id]);
                    setn_geoip_output(cfg, r, "GEOIP_CONTINENT_CODE",
                                      GeoIP_country_continent[country_id]);
                }
                if (giregion->region[0]) {
                    set_geoip_output(cfg, r, "GEOIP_REGION", giregion->region);
                }
                if (region_name != NULL) {
                    set_geoip_output(cfg, r, "GEOIP_REGION_NAME", region_name);
                }
                GeoIPRegion_delete(giregion);
            }
            break;
        case GEOIP_CITY_EDITION_REV0_V6:
        case GEOIP_CITY_EDITION_REV1_V6:
            gir = GeoIP_record_by_addr_v6(cfg->gips[i], ipaddr);
            if (gir != NULL) {
                if (gir->country_code != NULL) {
                    region_name =
                        GeoIP_region_name_by_code(gir->country_code,
                                                  gir->region);
                }
                sprintf(metrocodestr, "%d", gir->dma_code);
                sprintf(areacodestr, "%d", gir->area_code);
                set_geoip_output(cfg, r, "GEOIP_CONTINENT_CODE_V6",
                                  gir->continent_code);
                set_geoip_output(cfg, r, "GEOIP_COUNTRY_CODE_V6",
                                  gir->country_code);
                set_geoip_output(cfg, r, "GEOIP_COUNTRY_NAME_V6",
                                  gir->country_name);
                set_geoip_output(cfg, r, "GEOIP_REGION_V6", gir->region);
                set_geoip_output(cfg, r, "GEOIP_REGION_NAME_V6", region_name);
                set_geoip_output(cfg, r, "GEOIP_CITY_V6", gir->city);
                set_geoip_output(cfg, r, "GEOIP_DMA_CODE_V6", metrocodestr);
                set_geoip_output(cfg, r, "GEOIP_METRO_CODE_V6", metrocodestr);
                set_geoip_output(cfg, r, "GEOIP_AREA_CODE_V6", areacodestr);
                sprintf(latstr, "%f", gir->latitude);
                sprintf(lonstr, "%f", gir->longitude);
                set_geoip_output(cfg, r, "GEOIP_LATITUDE_V6", latstr);
                set_geoip_output(cfg, r, "GEOIP_LONGITUDE_V6", lonstr);

                set_geoip_output(cfg, r, "GEOIP_POSTAL_CODE_V6",
                                  gir->postal_code);
                GeoIPRecord_delete(gir);
            }

            break;
        case GEOIP_CITY_EDITION_REV0:
        case GEOIP_CITY_EDITION_REV1:
            gir = GeoIP_record_by_addr(cfg->gips[i], ipaddr);
            if (gir != NULL) {
                if (gir->country_code != NULL) {
                    region_name =
                        GeoIP_region_name_by_code(gir->country_code,
                                                  gir->region);
                }
                sprintf(metrocodestr, "%d", gir->dma_code);
                sprintf(areacodestr, "%d", gir->area_code);
                set_geoip_output(cfg, r, "GEOIP_CONTINENT_CODE",
                                  gir->continent_code);
                set_geoip_output(cfg, r, "GEOIP_COUNTRY_CODE",
                                  gir->country_code);
                set_geoip_output(cfg, r, "GEOIP_COUNTRY_NAME",
                                  gir->country_name);
                set_geoip_output(cfg, r, "GEOIP_REGION", gir->region);
                set_geoip_output(cfg, r, "GEOIP_REGION_NAME", region_name);
                set_geoip_output(cfg, r, "GEOIP_CITY", gir->city);
                set_geoip_output(cfg, r, "GEOIP_DMA_CODE", metrocodestr);
                set_geoip_output(cfg, r, "GEOIP_METRO_CODE", metrocodestr);
                set_geoip_output(cfg, r, "GEOIP_AREA_CODE", areacodestr);
                sprintf(latstr, "%f", gir->latitude);
                sprintf(lonstr, "%f", gir->longitude);
                set_geoip_output(cfg, r, "GEOIP_LATITUDE", latstr);
                set_geoip_output(cfg, r, "GEOIP_LONGITUDE", lonstr);
                set_geoip_output(cfg, r, "GEOIP_POSTAL_CODE",
                                  gir->postal_code);
                GeoIPRecord_delete(gir);
            }

            break;
        case GEOIP_ORG_EDITION:
            orgorisp = GeoIP_name_by_addr(cfg->gips[i], ipaddr);
            setn_geoip_output(cfg, r, "GEOIP_ORGANIZATION", orgorisp);
            break;
        case GEOIP_ISP_EDITION:
            orgorisp = GeoIP_name_by_addr(cfg->gips[i], ipaddr);
            setn_geoip_output(cfg, r, "GEOIP_ISP", orgorisp);
            break;
        case GEOIP_DOMAIN_EDITION:
            orgorisp = GeoIP_name_by_addr(cfg->gips[i], ipaddr);
            setn_geoip_output(cfg, r, "GEOIP_DOMAIN", orgorisp);
            break;
        }
    }

    if (free_me)
        free(free_me);
    return OK;
}
예제 #28
0
/**
 * \internal
 * \brief This function is used to initialize the geolocation MaxMind engine
 *
 * \retval NULL if the engine couldn't be initialized
 * \retval (GeoIP *) to the geolocation engine
 */
static GeoIP *InitGeolocationEngine(void)
{
    return GeoIP_new(GEOIP_MEMORY_CACHE);
}