Exemplo n.º 1
0
void load_db_file(prolog_database *db, const char *file_name, long offset)
{
	FILE *f;
	f = safe_fopen(file_name, "rb");
	load_db(db, f, offset, file_load);
	fclose(f);
}
Exemplo n.º 2
0
BOOL read_build_check(int i){
	BOOL flag = load_db(i);
	if(!flag) return 0;
	build_dir(i);
	FilesIterate(g_rootVols[i],(pFileVisitor)check_file_entry,&flag);
	return 1;
}
Exemplo n.º 3
0
nevera_fsm_t* new_nevera_fsm(fsm_trans_t* nevera_transition_table){
	nevera_fsm_t* nevera_fsm = (nevera_fsm_t*)malloc(sizeof(nevera_fsm_t));
	nevera_fsm->fsm.tt = nevera_transition_table;
	nevera_fsm->fsm.current_state = START;
	nevera_fsm->lista_usuarios = usuario_list_init();
	nevera_fsm->lista_productos  = producto_list_init();
	nevera_fsm->db = load_db(nevera_fsm->lista_usuarios,nevera_fsm->lista_productos);
	return nevera_fsm;
}
Exemplo n.º 4
0
//========================================================================================
void HvCrate::s_load_process(char *load_file){ //_db

 FILE *fp;
// fp=fopen("/misc/clas/clas12/R3.14.12.3/epicsqt-1.1.2-src/hv_control/db_config.txt","r");
 //fp=fopen("db_config.txt","r");
  fp=fopen(load_file,"r");
 if(!fp){printf("config files open failure (load fp) \n"); exit(1);}

 char line[400];
 int br;
 int ch;

 //char pars[20][15]; // 20 params, 20 characters long
 while(fgets(line,400,fp)){
  // strcat(line, " ");
   for(int i=0;i<(int)strlen(line);i++){
       if(line[i]==10 || line[i]==13)line[i]=0;
   }
   strcat(line, " ");

     string s=string(line);
   size_t pos = 0;
   //std::string token;
   size_t pos1=0;
   vector<string> ps;
  // printf("loading 0\n"); fflush(stdout);
   while ((pos = s.find(" ", pos1)) != std::string::npos) {
     // printf("loading 1\n"); fflush(stdout); sleep(1);
     if(pos1 != 0 && pos==pos1){pos1=pos+1;continue;}
     //printf("loading 2\n"); fflush(stdout); sleep(1);
     ps.push_back(s.substr(pos1, pos));
     pos1=pos+1;
   }
 //  printf("loading %d %d\n", strlen(s.c_str()), pos1); fflush(stdout);
  // if((pos1+1) != strlen(s.c_str()))
     //  ps.push_back(s.substr(pos1));
  // printf("loading size=%d\n",ps.size()); fflush(stdout);
   for(size_t i=0;i<ps.size();i++){
     if(i==0){
      pos = ps[i].find(".", 0);
      br=atoi((ps[i].substr(0,pos)).c_str());
      ch=atoi((ps[i].substr(pos+1)).c_str());
     }
     else{

         load_db( br, ch, i, ps );
     }
   }
 }


 fclose(fp);
// printf("end of loading\n");fflush(stdout);
}
Exemplo n.º 5
0
Arquivo: txt.c Projeto: aahls/txt
/*
This sets the working directory. save_db() calls rely on the working directory
being unchanged after the call. Probably shouldn't rely on that side effect
*/
note_db_t get_db(enum db which_db){
    if(which_db==DB_GLOBAL){
        chdir(getenv("HOME"));
    }else if(which_db==DB_STD){
        char cwd[1024];
        while(access(NOTESFILE, F_OK) == -1){
            if(!strcmp(getcwd(cwd, 1024), "/")){
                chdir(getenv("HOME"));
                break;
            }
            chdir("..");
        }
    }
    if(access(NOTESFILE, F_OK) != -1)
        return load_db(NOTESFILE);
    else
        return empty_db();
}
Exemplo n.º 6
0
/* -------------------------------------------------------------
// ------   MAIN - replace this by your own aplication! 
// ------------------------------------------------------------- */
int main(int argn, char *argv[]) {
  int multipnm=1;
  job_t job1, *job; /* fixme, dont want global variables for lib */
  job=OCR_JOB=&job1;

  setvbuf(stdout, (char *) NULL, _IONBF, 0);	/* not buffered */

  job_init(job); /* init cfg and db */

  process_arguments(job, argn, argv);
  
  /* load character data base (JS1002: now outside pgm2asc) */
  if ( job->cfg.mode & 2 ) /* check for db-option flag */
    load_db(job);
    /* load_db uses readpnm() and would conflict with multi images */
        
  while (multipnm==1) { /* multi-image loop */

    job_init_image(job); /* single image */

    mark_start(job);

    multipnm = read_picture(job);
    /* separation of main and rest for using as lib
       this will be changed later => introduction of set_option()
       for better communication to the engine  */
    if (multipnm<0) break; /* read error */
  
    /* call main loop */
    pgm2asc(job);

    mark_end(job);
  
    print_output(job);

    job_free_image(job);

  }

  return ((multipnm<0)?multipnm:0); /* -1=255 on error, 0 ok */
}
Exemplo n.º 7
0
/* reload DB cache
 * return value
 *   0: success
 *  -1: error
 */
int reload_im_cache(void)
{
	im_entry_t	**hash, **old_hash;
	int	ret;

	/* make sure that there is no other writer process */
	writer_lock_imhash();

	if (!(hash = new_im_hash())) {
		writer_release_imhash();
		return -1;
	}
	ret = load_db(hash);

	if (ret == -1) {
		/* error occured */
		LOG(L_ERR, "ERROR: reload_im_cache(): could not reload cache\n");
		free_im_hash(hash); /* there can be data in the hash already */
		writer_release_imhash();
		return -1;

	} else if (ret == -2) {
		/* SQL table was empty -- drop hash table */
		delete_im_hash(hash);
		hash = NULL;
	}

	old_hash = IM_HASH->entries;

	/* ask reader processes to stop reading */
	set_wd_imhash();
	IM_HASH->entries = hash;
	del_wd_imhash();

	if (old_hash) free_im_hash(old_hash);

	writer_release_imhash();
	return 0;
}
Exemplo n.º 8
0
char* gocr_main(job_t* job) {
  int multipnm=1;
  char* output;
  setvbuf(stdout, (char *) NULL, _IONBF, 0);	/* not buffered */

  /* load character data base (JS1002: now outside pgm2asc) */
  if ( job->cfg.mode & 2 ) /* check for db-option flag */
    load_db(job);
    /* load_db uses readpnm() and would conflict with multi images */

  while (multipnm==1) { /* multi-image loop */

    job_init_image(job); /* single image */

    mark_start(job);

    multipnm = read_picture(job);
    /* separation of main and rest for using as lib
       this will be changed later => introduction of set_option()
       for better communication to the engine  */
    if (multipnm<0) break; /* read error */

    /* call main loop */
    pgm2asc(job);

    mark_end(job);

    output = print_output(job);

    job_free_image(job);

  }

//  return ((multipnm<0)?multipnm:0); /* -1=255 on error, 0 ok */
    return output;
}
Exemplo n.º 9
0
int CLAMAPI Scan_Initialize(const wchar_t *pEnginesFolder, const wchar_t *pTempRoot, const wchar_t *pLicenseKey, BOOL bLoadMinDefs) {
    BOOL cant_convert;
    int ret;

    logg("*in Scan_Initialize(pEnginesFolder = %S, pTempRoot = %S)\n", pEnginesFolder, pTempRoot);
    if(!pEnginesFolder)
	FAIL(CL_ENULLARG, "pEnginesFolder is NULL");
    if(!pTempRoot)
	FAIL(CL_ENULLARG, "pTempRoot is NULL");
    if(lock_engine())
	FAIL(CL_ELOCK, "failed to lock engine");
    if(engine) {
	unlock_engine();
	FAIL(CL_ESTATE, "Already initialized");
    }

    if(!(engine = cl_engine_new())) {
	unlock_engine();
	FAIL(CL_EMEM, "Not enough memory for a new engine");
    }
    cl_engine_set_clcb_pre_cache(engine, filetype_cb);
    cl_engine_set_clcb_pre_scan(engine, prescan_cb);
    cl_engine_set_clcb_post_scan(engine, postscan_cb);
    
    minimal_definitions = bLoadMinDefs;
    if(bLoadMinDefs)
	logg("^MINIMAL DEFINITIONS MODE ON!\n");

    if(!WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, pTempRoot, -1, tmpdir, sizeof(tmpdir), NULL, &cant_convert) || cant_convert) {
	free_engine_and_unlock();
	FAIL(CL_EARG, "Can't translate pTempRoot");
    }
    ret = strlen(tmpdir);
    while(ret>0 && tmpdir[--ret] == '\\')
	tmpdir[ret] = '\0';
    if(!ret || ret + 8 + 1 >= sizeof(tmpdir)) {
	free_engine_and_unlock();
	FAIL(CL_EARG, "Bad or too long pTempRoot '%s'", tmpdir);
    }
    memcpy(&tmpdir[ret+1], "\\clamtmp", 9);
    cli_rmdirs(tmpdir);
    if((ret = SHCreateDirectoryExA(NULL, tmpdir, NULL) != ERROR_SUCCESS) && ret != ERROR_ALREADY_EXISTS) {
	free_engine_and_unlock();
	FAIL(CL_ETMPDIR, "Cannot create pTempRoot '%s': error %d", tmpdir, ret);
    }
    if((ret = cl_engine_set_str(engine, CL_ENGINE_TMPDIR, tmpdir))) {
	free_engine_and_unlock();
	FAIL(ret, "Failed to set engine tempdir to '%s': %s", tmpdir, cl_strerror(ret));
    }
    if(!WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, pEnginesFolder, -1, dbdir, sizeof(dbdir), NULL, &cant_convert) || cant_convert) {
	free_engine_and_unlock();
	FAIL(CL_EARG, "Can't translate pEnginesFolder");
    }
    ret = load_db();
    unlock_engine();

    if(!ret) {
	ResetEvent(monitor_event);
	if(!(monitor_hdl = CreateThread(NULL, 0, monitor_thread, NULL, 0, NULL)))
	    logg("^Failed to start db monitoring thread\n");
    }

    logg("*Scan_Initialize: returning %d\n", ret);
    return ret;
}
Exemplo n.º 10
0
CLAMAPI void Scan_ReloadDatabase(BOOL bLoadMinDefs) {
    if(InterlockedIncrement(&reload_waiters)==1) {
	int reload_ok = 0;
	logg("*Scan_ReloadDatabase: Database reload requested received, waiting for idle state\n");
	while(1) {
	    unsigned int i;
	    struct cl_settings *settings;

	    if(WaitForSingleObject(reload_event, INFINITE) == WAIT_FAILED) {
		logg("!Scan_ReloadDatabase: failed to wait on reload event\n");
		continue;
	    }
	    logg("*Scan_ReloadDatabase: Now idle, acquiring engine lock\n");
	    if(lock_engine()) {
		logg("!Scan_ReloadDatabase: failed to lock engine\n");
		break;
	    }
	    if(!engine) {
		logg("!Scan_ReloadDatabase: engine is NULL\n");
		unlock_engine();
		break;
	    }
	    logg("*Scan_ReloadDatabase: Engine locked, acquiring instance lock\n");
	    if(lock_instances()) {
		logg("!Scan_ReloadDatabase: failed to lock instances\n");
		unlock_engine();
		break;
	    }
            for(i=0; i<ninsts_total; i++) {
		if(instances[i].inst && instances[i].refcnt)
		    break;
	    }
	    if(i!=ninsts_total) {
		logg("Scan_ScanObjectByHandle: some instances are still in use\n");
		ResetEvent(reload_event);
		unlock_instances();
		unlock_engine();
		continue;
	    }
	    settings = cl_engine_settings_copy(engine);
	    if (!settings) {
		logg("!Scan_ReloadDatabase: Not enough memory for engine settings\n");
		unlock_instances();
		unlock_engine();
		break;
	    }

	    logg("Scan_ReloadDatabase: Destroying old engine\n");
	    cl_engine_free(engine);
	    minimal_definitions = bLoadMinDefs;
	    logg("Scan_ReloadDatabase: Loading new engine\n");

	    // NEW STUFF //
	    if(!(engine = cl_engine_new())) {
		logg("!Scan_ReloadDatabase: Not enough memory for a new engine\n");
		unlock_instances();
		unlock_engine();
		break;
	    }
	    cl_engine_settings_apply(engine, settings);
	    cl_engine_settings_free(settings);

	    load_db(); /* FIXME: FIAL? */
	    unlock_instances();
	    unlock_engine();
	    reload_ok = 1;
	    break;
	}
	if(reload_ok)
	    logg("Scan_ReloadDatabase: Database successfully reloaded\n");
	else
	    logg("!Scan_ReloadDatabase: Database reload failed\n");
    } else
	logg("*Database reload requested received while reload is pending\n");
    InterlockedDecrement(&reload_waiters);
}
Exemplo n.º 11
0
Arquivo: main.c Projeto: borlak/acmud
// game boot up stuff
void init_mud(long hotreboot)
{
	char buf[MAX_BUFFER];
	MSOCKET *socket;
	extern CREATURE *hash_creature[HASH_KEY];
	extern OBJECT *hash_object[HASH_KEY];
	extern ROOM *hash_room[HASH_KEY];
	extern char **connect_attempts;
	extern void backup_update();
#ifndef WIN32
	struct itimerval itime;
	struct timeval time;
#endif
	extern char * const months[];
	extern char * const days[];
	long x;

	for(x = 0; months[x]; x++) ;
	mudtime.months = x;
	for(x = 0; days[x]; x++) ;
	mudtime.days = x;

	// init hash tables
	memset(hash_creature,	0,sizeof(hash_creature));
	memset(hash_object,	0,sizeof(hash_object));
	memset(hash_room,	0,sizeof(hash_room));
	memset(hash_reset,	0,sizeof(hash_reset));

	// set up process signals to catch and deal with
	signal(SIGINT,		signal_handler);
	signal(SIGILL,		signal_handler);
	signal(SIGFPE,		signal_handler);

	signal(SIGSEGV,		signal_handler);
	signal(SIGPIPE,		SIG_IGN);	// ignore pipes! tx to unix socket faq for help
						// with this.  http://http://www.developerweb.net/forum/
#ifndef WIN32
	signal(SIGTRAP,		signal_handler);
	signal(SIGVTALRM,	signal_handler);

	// this code is to check for infinite looping
	time.tv_sec		= 5;
	time.tv_usec		= 0;
	itime.it_interval	= time;
	itime.it_value		= time;
	if( setitimer(ITIMER_VIRTUAL, &itime, 0) < 0 )
		mudlog("Error starting setitimer.");
#endif

	// initialize the random number generator
	init_rand();

	// connect_attempts array, to keep people from spam connecting to slow down the mud
        connect_attempts        = malloc(sizeof(char*));
        connect_attempts[0]     = 0;

	mysql = mysql_init(NULL);       
       if (!mysql)
       {
               mudlog("Error initializing MySQL: %s", mysql_error(mysql));
               abort();
       }

        // connect to MySQL database
       if (!mysql_real_connect(mysql, DB_HOST, DB_LOGIN, DB_PASSWORD, DB_NAME, 0, NULL, 0))
        {
               mudlog("Error opening mysql database: %s", mysql_error(mysql));
                abort();
        }

        if (mysql_select_db(mysql, DB_NAME))
        {
               mudlog("Error opening main database: %s",mysql_error(mysql));
               if (mysql)
                       mysql_close(mysql);
                abort();
        }

	// time of da mud !
	fread_time();

	// load areas/rooms/objects/creatures
	load_db();

	// check if hotreboot and reconnect everything
	if(hotreboot)
	{
		MSOCKET *socket=0;
		char buf[MAX_BUFFER];
		MYSQL_RES *result;
		MYSQL_ROW row;

		mysql_query(mysql, "SELECT * FROM player WHERE online='1'");
		result = mysql_store_result(mysql);

		if (mysql_num_rows(result) < 0)
		{
			mudlog("hotreboot: mysql error is: %s",mysql_error(mysql));
			exit(1);
		}

		while((row = mysql_fetch_row(result)))
		{
			strcpy(buf, row[P_NAME]);

			// check for "host" player.. holds control descriptor
			if(!strcasecmp("host", row[C_NAME]))
			{
				host = atoi(row[P_DESCRIPTOR]);
			}
			else
			{
				socket = init_socket();
				fread_player(socket, buf);

				str_dup(&socket->host,		row[P_HOST]);
				str_dup(&socket->ip,		row[P_IP]);

				socket->desc = atoi(row[P_DESCRIPTOR]);
				socket->connected = CON_PLAYING;

				trans(socket->pc, socket->pc->in_room);

				sendcrit(socket->pc, "Hotreboot completed.");
			}
		}
		mysql_free_result(result);
	}

	// make sure nobody has non-existant connections, in the event of a crash + hotreboot
	// then go through and update people who are online
	// this is also a good time to get host address, as players will be expecting lag
	mysql_query(mysql, "UPDATE player SET online='0', descriptor='0'");

	for(socket = socket_list; socket; socket = socket->next)
	{
		get_hostname(socket);
		sprintf(buf,"UPDATE player SET online='1', host=\"%s\" WHERE id='%li'",
			smash_quotes(socket->host), socket->id);
		mysql_query(mysql, buf);
	}

	// see how many players are in each area, to see if area should be 'alive'
	for(socket = socket_list; socket; socket = socket->next)
	{
		if(IsPlaying(socket->pc))
			socket->pc->in_room->area->players++;
	}

	// check if we need to backup
	backup_update();
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
	int arp_sockfd, arp_getlen, i;
	int send_count=0, file_num=0;
	struct sockaddr_in router_addr, device_addr;
	char router_ipaddr[17], router_mac[17], buffer[ARP_BUFFER_SIZE];
	unsigned char scan_ipaddr[4]; // scan ip
	FILE *fp_ip, *fp;
	fd_set rfds;
	ARP_HEADER * arp_ptr;
	struct timeval tv1, tv2, arp_timeout;
	int shm_client_detail_info_id;
	int ip_dup, mac_dup, real_num;
	int lock;
	int ret;
	int pid, flag;	//Andy Chiu, 2015/06/16. Checking the networkmap exist.
	unsigned short msg_type;
#if defined(RTCONFIG_QCA) && defined(RTCONFIG_WIRELESSREPEATER)	
	char *mac;
#endif

	signal(SIGTERM, nwmap_sig_term);	//Andy Chiu, 2015/06/12. Add for terminate signal handling
	loop = 1;

	//Andy Chiu, 2015/06/16. check otehr networkmap exist.
	flag = 0;
	fp = fopen("/var/run/networkmap.pid", "r");
	if(fp)
	{
		if(fscanf(fp, "%d", &pid) > 0)
		{
			sprintf(buffer, "/proc/%d", pid);
			if(!access(buffer, F_OK))
				flag = 1;
		}
		fclose(fp);
	}
	
	if(flag)
	{
		NMP_DEBUG("[%s, %d]networkmap is already running now.\n", __FUNCTION__, __LINE__);
		return 0;
	}
	
	fp = fopen("/var/run/networkmap.pid", "w");
	if(fp != NULL){
		fprintf(fp, "%d", getpid());
		fclose(fp);
	}
#ifdef DEBUG
	eval("rm", "/var/client*");
#endif

	//Initial client tables
	lock = file_lock("networkmap");
	shm_client_detail_info_id = shmget((key_t)1001, sizeof(CLIENT_DETAIL_INFO_TABLE), 0666|IPC_CREAT);
	if (shm_client_detail_info_id == -1){
		fprintf(stderr,"shmget failed\n");
		file_unlock(lock);
		exit(1);
	}

	CLIENT_DETAIL_INFO_TABLE *p_client_detail_info_tab = (P_CLIENT_DETAIL_INFO_TABLE)shmat(shm_client_detail_info_id,(void *) 0,0);
	//Reset shared memory
	memset(p_client_detail_info_tab, 0x00, sizeof(CLIENT_DETAIL_INFO_TABLE));
	p_client_detail_info_tab->ip_mac_num = 0;
	p_client_detail_info_tab->detail_info_num = 0;
	file_unlock(lock);

#ifdef NMP_DB
	nmp_client_list = NULL;
	if(!load_db(&nmp_client_list) && nmp_client_list)
		NMP_DEBUG_M("NMP Client:\n%s\n", nmp_client_list);
	signal(SIGUSR2, reset_db);
#endif

	//Get Router's IP/Mac
	//Andy Chiu, 2014/10/22.
	tcapi_get("Info_Ether", "ip", router_ipaddr);
	tcapi_get("Info_Ether", "mac", router_mac);
	inet_aton(router_ipaddr, &router_addr.sin_addr);
	memcpy(my_ipaddr,  &router_addr.sin_addr, 4);

	//Prepare scan 
	networkmap_fullscan = 1;
	//Andy Chiu, 2014/10/22.
	if(tcapi_set("ClientList_Common", "scan", "1"))
		NMP_DEBUG_M("set node(ClientList_Common:scan) failed.\n");

	if (argc > 1) {
		if (strcmp(argv[1], "--bootwait") == 0) {
			sleep(30);

			//Andy Chiu, 2014/12/09
			if(!access("/var/static_arp_tbl.sh", F_OK))
			system("/var/static_arp_tbl.sh");
		}
	}
	if (strlen(router_mac)!=0) ether_atoe(router_mac, my_hwaddr);

	signal(SIGUSR1, refresh_sig); //catch UI refresh signal

	// create UDP socket and bind to "br0" to get ARP packet//
	arp_sockfd = create_socket(INTERFACE);

	if(arp_sockfd < 0)
		perror("create socket ERR:");
	else {
		arp_timeout.tv_sec = 0;
		arp_timeout.tv_usec = 50000;
		setsockopt(arp_sockfd, SOL_SOCKET, SO_RCVTIMEO, &arp_timeout, sizeof(arp_timeout));//set receive timeout
		dst_sockll = src_sockll; //Copy sockaddr info to dst
		memset(dst_sockll.sll_addr, -1, sizeof(dst_sockll.sll_addr)); // set dmac= FF:FF:FF:FF:FF:FF
	}

	while(loop)//main while loop
	{
		while(loop) { //full scan and reflush recv buffer
fullscan:
			if(networkmap_fullscan == 1) { //Scan all IP address in the subnetwork
				if(scan_count == 0) { 
					eval("asusdiscovery");	//find asus device
					// (re)-start from the begining
					memset(scan_ipaddr, 0x00, 4);
					memcpy(scan_ipaddr, &router_addr.sin_addr, 3);
					arp_timeout.tv_sec = 0;
					arp_timeout.tv_usec = 50000;
					setsockopt(arp_sockfd, SOL_SOCKET, SO_RCVTIMEO, &arp_timeout, sizeof(arp_timeout));//set receive timeout
					NMP_DEBUG("Starting full scan!\n");
					//Andy Chiu, 2014/10/22. remove unused flag, "refresh_networkmap".
#if 0
					if(nvram_match("refresh_networkmap", "1"))  //reset client tables
					{
						lock = file_lock("networkmap");
						memset(p_client_detail_info_tab, 0x00, sizeof(CLIENT_DETAIL_INFO_TABLE));
						//p_client_detail_info_tab->detail_info_num = 0;
						//p_client_detail_info_tab->ip_mac_num = 0;
						file_unlock(lock);
						nvram_unset("refresh_networkmap");
					}
					else {
						int x = 0;
						for(; x<255; x++)
						p_client_detail_info_tab->exist[x]=0;
					}
#else
					memset(p_client_detail_info_tab, 0x00, sizeof(CLIENT_DETAIL_INFO_TABLE));
#endif
				}
				scan_count++;
				scan_ipaddr[3]++;

				if( scan_count<255 && memcmp(scan_ipaddr, my_ipaddr, 4) ) {
					sent_arppacket(arp_sockfd, scan_ipaddr);
				}         
				else if(scan_count==255) { //Scan completed
					arp_timeout.tv_sec = 2;
					arp_timeout.tv_usec = 0; //Reset timeout at monitor state for decase cpu loading
					setsockopt(arp_sockfd, SOL_SOCKET, SO_RCVTIMEO, &arp_timeout, sizeof(arp_timeout));//set receive timeout
					networkmap_fullscan = 0;
					//scan_count = 0;
					//nvram_set("networkmap_fullscan", "0");
					if(tcapi_set("ClientList_Common", "scan", "0"))
						NMP_DEBUG_M("set node(ClientList_Common:scan) failed.\n");
					NMP_DEBUG("Finish full scan!\n");
				}
			}// End of full scan

			memset(buffer, 0, ARP_BUFFER_SIZE);
			arp_getlen=recvfrom(arp_sockfd, buffer, ARP_BUFFER_SIZE, 0, NULL, NULL);

			if(arp_getlen == -1) {
				if( scan_count<255)
					goto fullscan;
				else
					break;
			}
			else {
				arp_ptr = (ARP_HEADER*)(buffer);
				NMP_DEBUG("*Receive an ARP Packet from: %d.%d.%d.%d to %d.%d.%d.%d:%02X:%02X:%02X:%02X - len:%d\n",
					(int *)arp_ptr->source_ipaddr[0],(int *)arp_ptr->source_ipaddr[1],
					(int *)arp_ptr->source_ipaddr[2],(int *)arp_ptr->source_ipaddr[3],
					(int *)arp_ptr->dest_ipaddr[0],(int *)arp_ptr->dest_ipaddr[1],
					(int *)arp_ptr->dest_ipaddr[2],(int *)arp_ptr->dest_ipaddr[3],
					arp_ptr->dest_hwaddr[0],arp_ptr->dest_hwaddr[1],
					arp_ptr->dest_hwaddr[2],arp_ptr->dest_hwaddr[3],
					arp_getlen);

				//Check ARP packet if source ip and router ip at the same network
				if( !memcmp(my_ipaddr, arp_ptr->source_ipaddr, 3) ) {
					msg_type = ntohs(arp_ptr->message_type);

					if( //ARP packet to router
						( msg_type == 0x02 &&   		       	// ARP response
						memcmp(arp_ptr->dest_ipaddr, my_ipaddr, 4) == 0 && 	// dest IP
						memcmp(arp_ptr->dest_hwaddr, my_hwaddr, 6) == 0) 	// dest MAC
						||
						(msg_type == 0x01 &&                    // ARP request
						memcmp(arp_ptr->dest_ipaddr, my_ipaddr, 4) == 0)    // dest IP
						){
							//NMP_DEBUG("   It's an ARP Response to Router!\n");
							NMP_DEBUG("*RCV %d.%d.%d.%d-%02X:%02X:%02X:%02X:%02X:%02X\n",
								arp_ptr->source_ipaddr[0],arp_ptr->source_ipaddr[1],
								arp_ptr->source_ipaddr[2],arp_ptr->source_ipaddr[3],
								arp_ptr->source_hwaddr[0],arp_ptr->source_hwaddr[1],
								arp_ptr->source_hwaddr[2],arp_ptr->source_hwaddr[3],
								arp_ptr->source_hwaddr[4],arp_ptr->source_hwaddr[5]);

							for(i=0; i<p_client_detail_info_tab->ip_mac_num; i++) {
								ip_dup = memcmp(p_client_detail_info_tab->ip_addr[i], arp_ptr->source_ipaddr, 4);
								mac_dup = memcmp(p_client_detail_info_tab->mac_addr[i], arp_ptr->source_hwaddr, 6);

								if((ip_dup == 0) && (mac_dup == 0)) {
									lock = file_lock("networkmap");
									p_client_detail_info_tab->exist[i] = 1;
									file_unlock(lock);
									break;
								}
								else if((ip_dup != 0) && (mac_dup != 0)) {
									continue;
								}
								else if( (scan_count>=255) && ((ip_dup != 0) && (mac_dup == 0)) ) { 
									NMP_DEBUG("IP changed, update immediately\n");
									NMP_DEBUG("*CMP %d.%d.%d.%d-%02X:%02X:%02X:%02X:%02X:%02X\n",
										p_client_detail_info_tab->ip_addr[i][0],p_client_detail_info_tab->ip_addr[i][1],
										p_client_detail_info_tab->ip_addr[i][2],p_client_detail_info_tab->ip_addr[i][3],
										p_client_detail_info_tab->mac_addr[i][0],p_client_detail_info_tab->mac_addr[i][1],
										p_client_detail_info_tab->mac_addr[i][2],p_client_detail_info_tab->mac_addr[i][3],
										p_client_detail_info_tab->mac_addr[i][4],p_client_detail_info_tab->mac_addr[i][5]);

									lock = file_lock("networkmap");
									memcpy(p_client_detail_info_tab->ip_addr[i],
										arp_ptr->source_ipaddr, 4);
									memcpy(p_client_detail_info_tab->mac_addr[i],
										arp_ptr->source_hwaddr, 6);
									p_client_detail_info_tab->exist[i] = 1;
									file_unlock(lock);
								/*
								real_num = p_client_detail_info_tab->detail_info_num;
								p_client_detail_info_tab->detail_info_num = i;
#ifdef NMP_DB
								check_nmp_db(p_client_detail_info_tab, i);
#endif
								FindAllApp(my_ipaddr, p_client_detail_info_tab);
								FindHostname(p_client_detail_info_tab);
								p_client_detail_info_tab->detail_info_num = real_num;
								*/
									break;
								}

							}
							//NMP_DEBUG("Out check!\n");
							//i=0, table is empty.
							//i=num, no the same ip at table.
							if(i==p_client_detail_info_tab->ip_mac_num){
								lock = file_lock("networkmap");
								memcpy(p_client_detail_info_tab->ip_addr[p_client_detail_info_tab->ip_mac_num], 
									arp_ptr->source_ipaddr, 4);
								memcpy(p_client_detail_info_tab->mac_addr[p_client_detail_info_tab->ip_mac_num], 
									arp_ptr->source_hwaddr, 6);
								p_client_detail_info_tab->exist[p_client_detail_info_tab->ip_mac_num] = 1;
#ifdef NMP_DB
								check_nmp_db(p_client_detail_info_tab, i);
#endif
								p_client_detail_info_tab->ip_mac_num++;
								file_unlock(lock);

#ifdef DEBUG  //Write client info to file
								fp_ip=fopen("/var/client_ip_mac.txt", "a");
								if (fp_ip==NULL) {
									NMP_DEBUG("File Open Error!\n");
								}
								else {
									NMP_DEBUG_M("Fill: %d-> %d.%d\n", i,p_client_detail_info_tab->ip_addr[i][2],p_client_detail_info_tab->ip_addr[i][3]);

									fprintf(fp_ip, "%d.%d.%d.%d,%02X:%02X:%02X:%02X:%02X:%02X\n",
									p_client_detail_info_tab->ip_addr[i][0],p_client_detail_info_tab->ip_addr[i][1],
									p_client_detail_info_tab->ip_addr[i][2],p_client_detail_info_tab->ip_addr[i][3],
									p_client_detail_info_tab->mac_addr[i][0],p_client_detail_info_tab->mac_addr[i][1],
									p_client_detail_info_tab->mac_addr[i][2],p_client_detail_info_tab->mac_addr[i][3],
									p_client_detail_info_tab->mac_addr[i][4],p_client_detail_info_tab->mac_addr[i][5]);
								}
								fclose(fp_ip);
#endif
							}
						}
						else { //Nomo ARP Packet or ARP response to other IP
							//Compare IP and IP buffer if not exist
							for(i=0; i<p_client_detail_info_tab->ip_mac_num; i++) {
								if( !memcmp(p_client_detail_info_tab->ip_addr[i], arp_ptr->source_ipaddr, 4) &&
									!memcmp(p_client_detail_info_tab->mac_addr[i], arp_ptr->source_hwaddr, 6)) {
									NMP_DEBUG_M("Find the same IP/MAC at the table!\n");
								break;
							}
						}
						if( i==p_client_detail_info_tab->ip_mac_num ) //Find a new IP or table is empty! Send an ARP request.
						{
							NMP_DEBUG("New device or IP/MAC changed!!\n");
							if(memcmp(my_ipaddr, arp_ptr->source_ipaddr, 4))
								sent_arppacket(arp_sockfd, arp_ptr->source_ipaddr);
							else
								NMP_DEBUG("New IP is the same as Router IP! Ignore it!\n");
						}
					}//End of Nomo ARP Packet
				}//Source IP in the same subnetwork
			}//End of arp_getlen != -1
		} // End of while for flush buffer

		if(!loop)
			break;
		
		/*
		int y = 0;
		while(p_client_detail_info_tab->type[y]!=0){
		NMP_DEBUG("%d: %d.%d.%d.%d,%02X:%02X:%02X:%02X:%02X:%02X,%s,%d,%d,%d,%d,%d\n", y ,
		p_client_detail_info_tab->ip_addr[y][0],p_client_detail_info_tab->ip_addr[y][1],
		p_client_detail_info_tab->ip_addr[y][2],p_client_detail_info_tab->ip_addr[y][3],
		p_client_detail_info_tab->mac_addr[y][0],p_client_detail_info_tab->mac_addr[y][1],
		p_client_detail_info_tab->mac_addr[y][2],p_client_detail_info_tab->mac_addr[y][3],
		p_client_detail_info_tab->mac_addr[y][4],p_client_detail_info_tab->mac_addr[y][5],
		p_client_detail_info_tab->device_name[y],
		p_client_detail_info_tab->type[y],
		p_client_detail_info_tab->http[y],
		p_client_detail_info_tab->printer[y],
		p_client_detail_info_tab->itune[y],
		p_client_detail_info_tab->exist[y]);
		y++;
		}
		*/
		//Find All Application of clients
		//NMP_DEBUG("\ndetail ? ip : %d ? %d\n\n", p_client_detail_info_tab->detail_info_num, p_client_detail_info_tab->ip_mac_num);
		if(p_client_detail_info_tab->detail_info_num < p_client_detail_info_tab->ip_mac_num) {
			//nvram_set("networkmap_status", "1");
			if(tcapi_set("ClientList_Common", "status", "1"))
				NMP_DEBUG_M("set node(ClientList_Common:status) failed.\n");
			FindAllApp(my_ipaddr, p_client_detail_info_tab);
			FindHostname(p_client_detail_info_tab);

#ifdef DEBUG //Fill client detail info table
			fp_ip=fopen("/var/client_detail_info.txt", "a");
			if (fp_ip==NULL) {
				NMP_DEBUG("File Open Error!\n");
			}
			else {
				fprintf(fp_ip, "%s,%d,%d,%d,%d\n",
				p_client_detail_info_tab->device_name[p_client_detail_info_tab->detail_info_num], 
				p_client_detail_info_tab->type[p_client_detail_info_tab->detail_info_num], 
				p_client_detail_info_tab->http[p_client_detail_info_tab->detail_info_num],
				p_client_detail_info_tab->printer[p_client_detail_info_tab->detail_info_num], 
				p_client_detail_info_tab->itune[p_client_detail_info_tab->detail_info_num]);
				fclose(fp_ip);
			}
#endif
#ifdef NMP_DB
			write_to_cfg_node(p_client_detail_info_tab);
#endif
			p_client_detail_info_tab->detail_info_num++;
		}
#ifdef NMP_DB
		else {
			NMP_DEBUG_M("commit_no, cli_no, updated: %d, %d, %d\n", 
			commit_no, p_client_detail_info_tab->detail_info_num, client_updated);
			if( (commit_no != p_client_detail_info_tab->detail_info_num) || client_updated ) {
				NMP_DEBUG("Commit nmp client list\n");
				//nvram_commit();
				commit_no = p_client_detail_info_tab->detail_info_num;
				client_updated = 0;
			}
		}
#endif

		if(p_client_detail_info_tab->detail_info_num == p_client_detail_info_tab->ip_mac_num)
		{
			//nvram_set("networkmap_status", "0");    // Done scanning and resolving
			NMP_DEBUG_M("Scan Finish!\n");
			if(tcapi_set("ClientList_Common", "status", "0"))
				NMP_DEBUG_M("set node(ClientList_Common:status) failed.\n");
		}
	} //End of main while loop
	SAFE_FREE(p_client_detail_info_tab);
	close(arp_sockfd);
	return 0;
}
Exemplo n.º 13
0
/*
 * __gtxt(catname, id, dflt): Return a pointer to a message.
 *	catname is the name of the catalog. If null, the default catalog is
 *		used.
 *	id is the numeric id of the message in the catalogue
 *	dflt is the default message.
 *
 *	Information about non-existent catalogues is kept in db_info, in
 *	such a way that subsequent calls with the same catalogue do not
 *	try to open the catalogue again.
 */
const char *
__gtxt(const char *catname, int id, const char *dflt)
{
	char	*curloc;
	struct db_info *db;
	int	err;

	/* Check for invalid message id */
	if (id < 0)
		return (not_found);
	if (id == 0)
		return ((dflt && *dflt) ? dflt : not_found);

	/*
	 * If catalogue is unspecified, use default catalogue.
	 * No catalogue at all is an error
	 */
	if (!catname || !*catname) {
		lrw_rdlock(&_rw_cur_cat);
		if (cur_cat == NULL || !*cur_cat) {
			lrw_unlock(&_rw_cur_cat);
			return (not_found);
		}
		catname = cur_cat;
		lrw_unlock(&_rw_cur_cat);
	}

	curloc = setlocale(LC_MESSAGES, NULL);

	/* First look up the cache */
	db = lookup_cache(NULL, curloc, catname);
	if (db != NULL) {
		/*
		 * The catalog has been loaded, and if id seems valid,
		 * then just return.
		 */
		if (valid_msg(db, id))
			return (msg(db, id));

		/*
		 * seems given id is out of bound or does not exist. In this
		 * case, we need to look up a message for the "C" locale as
		 * documented in the man page.
		 */
		db = lookup_cache(NULL, def_locale, catname);
		if (db == NULL) {
			/*
			 * Even the message catalog for the "C" has not been
			 * loaded.
			 */
			db = load_db(def_locale, catname, &err);
			if (err)
				return (not_found);
		}
		if (valid_msg(db, id))
			return (msg(db, id));
		/* no message found */
		return ((dflt && *dflt) ? dflt : not_found);
	}

	/*
	 * The catalog has not been loaded or even has not
	 * attempted to be loaded, invalidate all caches related to
	 * the catname for possibly different locale.
	 */
	db = NULL;
	while ((db = lookup_cache(db, NULL, catname)) != NULL)
		unload_db(db);

	/*
	 * load a message catalog for the requested locale.
	 */
	db = load_db(curloc, catname, &err);
	if (err)
		return (not_found);
	if (valid_msg(db, id))
		return (msg(db, id));

	/*
	 * If the requested catalog is either not exist or message
	 * id is invalid, then try to load from "C" locale.
	 */
	db = load_db(def_locale, catname, &err);
	if (err)
		return (not_found);

	if (valid_msg(db, id))
		return (msg(db, id));

	/* no message found */
	return ((dflt && *dflt) ? dflt : not_found);
}
Exemplo n.º 14
0
Arquivo: rarpd.c Projeto: OPSF/uClinux
void configure(void)
{
	load_if();
	load_db();
}
Exemplo n.º 15
0
Arquivo: lecs.c Projeto: ysleu/RTL8685
int main(int argc, char **argv)
{
  int i =0;
  char *config_file =NULL;
  char *listen_addr = NULL;
  int fd_arr[MAX_FD];
  int no_fds=1;
  int just_dump=0;
  fd_set fds;
  struct sockaddr_atmsvc client;
  int len;
  unsigned char buffer[P_SIZE];

  while(i!=-1) {
    i = getopt(argc, argv, "f:l:d");
    switch(i) {
    case 'd':
      printf("Dumping databasefile\n");
      just_dump=1;
      break;
    case 'f':
      if (config_file) {
	usage(argv[0]);
	exit(-1);
      }
      config_file = (char*)mem_alloc(COMP_NAME, strlen(optarg)+1);
      if (!config_file) {
	exit(-1);
      }
      memcpy(config_file, optarg, strlen(optarg)+1);
      break;
    case 'l':
      if (listen_addr) {
	usage(argv[0]);
	exit(-1);
      }
      listen_addr = (char*)mem_alloc(COMP_NAME, strlen(optarg)+1);
      if (!listen_addr)
	exit(-1);
      memcpy(listen_addr, optarg, strlen(optarg)+1);
      break;
    case -1:
      break;
    default:
      usage(argv[0]);
      exit(-1);
    }
  }
  if (argc != optind) {
    usage(argv[0]);
    exit(-1);
  }
  /* Following gets run in the beginning or when lecs is restarted */
  while (stay_alive) {

    /* Read configuration file */
    if (config_file) {
      if (load_db(config_file)<0)
	exit(-1);
    } else {
      if (load_db(DEFAULT_CONFIG)<0)
	exit(-1);
    }
    if (just_dump) {
      dump_db(NULL);
      exit(0);
    }

    /* Reserve signals */
    signal(SIGHUP, sig_reset);
    signal(SIGINT, sig_kill);
    signal(SIGQUIT, sig_kill);
    signal(SIGABRT, sig_kill);
    signal(SIGTERM, sig_kill);
    signal(SIGSEGV, sig_kill);
    
    /* CHANGE: First parameter, then configuration file! */
    fd_arr[0] = atm_create_socket(CONFIGURATION_DIRECT, 
				  get_lecs_addr());
    no_fds=1;
    if (fd_arr[0] <0) {
      stay_alive=0; /* No need to go on */
    }
    while(!reset && stay_alive) {
      FD_ZERO(&fds);
      for(i=0;i<no_fds;i++) {
	FD_SET(fd_arr[i],&fds);
      }
      
      if (select(MAX_FD, &fds, NULL, NULL, NULL)<0) {
	perror("select(MAX_FD,...)");
	stay_alive=0;
      } else {
	if (FD_ISSET(fd_arr[0],&fds)) { /* Incoming call */
	  if (no_fds == MAX_FD) {
	    close(fd_arr[1]); /* Oldest */
	    memmove(&fd_arr[1], &fd_arr[2], sizeof(int)*(MAX_FD-2));
	    no_fds--;
	  }
	  len = sizeof(client);
	  fd_arr[no_fds] = accept(fd_arr[0], (struct sockaddr*)&client,
				  &len);
	  if (fd_arr[no_fds]<0) {
	    if (errno==ENETRESET)
	      reset=1;
	    if (errno==EUNATCH)
	      stay_alive=1;
	  } else {
	    no_fds++;
	  }
	}
	for(i=1;i<no_fds;i++) {
	  if (FD_ISSET(fd_arr[i],&fds)) {
	    len = read(fd_arr[i], buffer, P_SIZE);
	    if (len <0 && (errno == ENETRESET || errno == EUNATCH)) {
	      reset=0;
	    }
	    if (len<=0) {
	      close(fd_arr[i]);
	      memmove(&fd_arr[i], &fd_arr[i+1], sizeof(int)*(--no_fds -i));
	      i--;
	    } else {
	      if(send_response(fd_arr[i], buffer, len)<0) {
		close(fd_arr[i]);
		memmove(&fd_arr[i], &fd_arr[i+1], sizeof(int)*(--no_fds -i));
	      }
	    }
	  }
	}
      }
    }
    /* This gets done if a signal has been caught, or if
       network resets/becomes unavailable */
    reset=0;
    for(i=0;i<no_fds;i++)
      close(fd_arr[i]);
    no_fds=0;
    reset_db();
  }
  return 0;
}
/* Основная функция */
int main() {
	# define ACTION(str) if (!strcmp(#str, action))
	setlocale(LC_ALL, "Ru");
	BookDB* db = NULL;
	char filename[MAX_STRING_LENGTH] = "\0";
	char action[MAX_STRING_LENGTH];
	print_hello();
	/* Цикл обработки событий */
	forever {
		printf("<! ");
		scanf("%s", action);
		
		ACTION(help) {
			print_help();
			continue;
		}
		
		ACTION(exit) {
			if (db) {
				close_db(db, filename);
				db = NULL;
				filename[0] = '\0';
			}
			break;
		}
		
		ACTION(close) {
			if (db) {
				close_db(db, filename);
				db = NULL;
				filename[0] = '\0';
				output("База данных закрыта!\n");
			} else db_not_loaded_error();
			continue;
		}
		
		ACTION(create) {
			if (db) {
				close_db(db, filename);
				filename[0] = '\0';
				db = NULL;
			}
			int n = 0;
			output("Предполагаемая размерность Базы Данных\n");
			input("%d", &n);
			db = create_db(n);
			output("База данных для %i элементов создана!\n", n);
			continue;
		}
		
		ACTION(load) {
			if (db) {
				close_db(db, filename);
				filename[0] = '\0';
				db = NULL;
			}
			do {
				output("Имя файла базы данных\n");
				input("%s", filename);
			} while (strlen(filename) < 1);
			db = load_db(filename);
			if (!db) {
				output("Неверное имя файла!\n");
				filename[0] = '\0';
			} else {
				output(">> База данных успешно загружена!\n");
			}
			continue;
		}
		
		ACTION(save) {
			if (db) {
				save_db_dialog(db, filename);
				output(">> База данных успешно сохранена!\n");
			} else db_not_loaded_error();
			continue;
		}
		
		ACTION(list) {
			if (db != 0) {
				list_db(db);
			} else db_not_loaded_error();
			continue;
		}
		
		ACTION(find) {
			if (db) {
				find_dialog(db);
			} else db_not_loaded_error();
			continue;
		}
		
		ACTION(new) {
			if (db) {
				new_dialog(db);
			} else db_not_loaded_error();
			continue;
		}
		
		ACTION(delete) {
			if (db) {
				delete_dialog(db);
			} else db_not_loaded_error();
			continue;
		}
		
		ACTION(size) {
			if (db) {
				output("Книг в базе данных - %d\n", db->count);
			} else db_not_loaded_error();
			continue;
		}
		
		ACTION(sort) {
			if (db) {
				sort_dialog(db);
			} else db_not_loaded_error();
			continue;
		}
		
		printf("!! Неизвестная команда \"%s\"\n", action);
	}
	# undef ACTION
	return 0;
}