/**
 * Convert a JavaScript Object to a map
 *
 * @param cx the JavaScript context
 * @param t the JavaScript Object to convert
 * @return a new map containing the JavaScript Object
 */
map* mapFromJSObject(JSContext *cx,jsval t){
  map *res=NULL;
  JSIdArray *idp=JS_Enumerate(cx,JSVAL_TO_OBJECT(t));
#ifdef JS_DEBUG
  fprintf(stderr,"Properties %p\n",(void*)t);
#endif
  if(idp!=NULL) {
    int index;
    jsdouble argNum;
#ifdef JS_DEBUG
    fprintf(stderr,"Properties length :  %d \n",idp->length);
#endif
    for (index=0,argNum=idp->length;index<argNum;index++) { 
      jsval id = idp->vector[index];
      jsval vp;
      JS_IdToValue(cx,id,&vp);
      char *tmp, *tmp1;
      JSString *jsmsg,*jsmsg1;
      size_t len,len1;
      jsmsg = JS_ValueToString(cx,vp);
      len = JS_GetStringLength(jsmsg);
      jsval nvp;
      tmp=JS_EncodeString(cx,jsmsg);
      JS_GetProperty(cx, JSVAL_TO_OBJECT(t), tmp, &nvp);
      jsmsg1 = JS_ValueToString(cx,nvp);
      len1 = JS_GetStringLength(jsmsg1);
      tmp1=JS_EncodeString(cx,jsmsg1);
#ifdef JS_DEBUG
      fprintf(stderr,"Enumerate id : %d [ %s => %s ]\n",index,tmp,tmp1);
#endif
      if(strcasecmp(tmp,"child")!=0){
	if(res!=NULL){
#ifdef JS_DEBUG
	  fprintf(stderr,"%s - %s\n",tmp,tmp1);
#endif
	  addToMap(res,tmp,tmp1);
	}
	else{
	  res=createMap(tmp,tmp1);
	  res->next=NULL;
	}
      }
      free(tmp);
      free(tmp1);
#ifdef JS_DEBUG
      dumpMap(res);
#endif
    }
    JS_DestroyIdArray(cx,idp);
  }
#ifdef JS_DEBUG
  dumpMap(res);
#endif
  return res;
}
Beispiel #2
0
static int proto_server_mt_dump_handler(Proto_Session *s)
{
    int rc;
    Proto_Msg_Hdr h;

    if (proto_debug()) {
        fprintf(stderr, "proto_server_mt_dump_handler: invoked for session:\n");
        //proto_session_dump(s);
    }

    dumpMap();

    // create replay message
    bzero(&h, sizeof(h));
    h.type = proto_session_hdr_unmarshall_type(s);
    h.type += PROTO_MT_REP_BASE_RESERVED_FIRST;
    proto_session_hdr_marshall(s, &h);

    rc = 1;
    if (proto_session_body_marshall_int(s, rc) < 0 )
        fprintf(stderr, "proto_server_mt_dump_handler: "
                "proto_session_body_marshall_bytes failed\n");

    rc = proto_session_send_msg(s, 1);
    // TODO: return failed if an error occours
    return rc;
}
Beispiel #3
0
value
ml_upnpDumpMaps(value unused)
{
	int i;
	ml_upnpmp_t * map;

	printf("=============== g_unmaps ===============\n");
	printf("enabled intPort extPort isTcp notes lanaddr upnpDscv upnpMapped upnpState natpmpDscv natpmpMapped natpmpState overTime natpmpStatus upnpStatus\n");
	for(i = 0; i < MAX_MAPS; i++ ){
		map = &g_unmaps[i];
		dumpMap( map, 0 );
	}
	printf("=============== g_maps ===============\n");
	printf("enabled intPort extPort isTcp notes lanaddr upnpDscv upnpMapped upnpState natpmpDscv natpmpMapped natpmpState overTime natpmpStatus upnpStatus\n");
	for(i = 0; i < MAX_MAPS; i++ ){
		map = &g_maps[i];
		dumpMap( map, 0 );
	}

	return Val_unit;
}
Beispiel #4
0
template<typename I, typename O> int denoiseNLMeans(std::string inputfile, EBitmapType inputtype, std::string outputfile, EBitmapType outputtype, int r = 3, int f = 1, Float k = 0.7, Float sigma = 0.1, bool dump = true) {
	NLMeansDenoiser<I, O> *denoiser = new NLMeansDenoiser<I, O>(sigma, dump);
	TBitmap<I> *input = new TBitmap<I>();
	if (!input->loadBitmap(inputfile, inputtype)){
		std::cout << "Input bitmap " << inputfile << " failed to load!\n";
		std::cin.get();
		return 0;
	}
	DenoiserInput<I> *dInput = new DenoiserInput<I>(outputfile);
	dInput->addImageBlock(new TImageBlock<I>(Point2i(0., 0.), input->getSize(), 1, false, input));
	DenoiserOutput<O> *dOutput = denoiser->denoise(dInput);
	LOG(EInfo, "Denoising finished. Time taken = %d seconds", dOutput->getDenoiseDuration());
	dumpMap(dOutput->getDenoisedImage()->getBitmap(), outputfile, outputtype);
	input->unloadBitmap();
	std::cin.get();
	_CrtDumpMemoryLeaks(); // prints mem leaks
	return 0;
}
Beispiel #5
0
template<typename I, typename O> int denoiseModifiedNLMeans(std::string inputfile, EBitmapType inputtype, std::string outputfile, EBitmapType outputtype, int r = 3, int f = 1, Float k = 0.7, Float sigma = 0.1, bool dump = true) {
	ModifiedNLMeansDenoiser<I, O> *denoiser = new ModifiedNLMeansDenoiser<I, O>(r, f, k, sigma, dump);
	TBitmap<I> *inputA = new TBitmap<I>;
	//BitmapI *inputsppA = new BitmapI;
	TBitmap<I> *inputsppA = new TBitmap<I>;
	TBitmap<I> *inputvarA = new TBitmap<I>;
	TBitmap<I> *inputvarsA = new TBitmap<I>;
	TBitmap<I> *inputB = new TBitmap<I>;
	//BitmapI *inputsppB = new BitmapI;
	TBitmap<I> *inputsppB = new TBitmap<I>;
	TBitmap<I> *inputvarB = new TBitmap<I>;
	TBitmap<I> *inputvarsB = new TBitmap<I>;
	Assert(inputA->loadBitmap(inputfile + "_A", inputtype), "Input bitmap A failed to load!");
	Assert(inputsppA->loadBitmap(inputfile + "_spp_A", inputtype), "Input spp bitmap A failed to load!");
	Assert(inputvarA->loadBitmap(inputfile + "_variance_A", inputtype), "Input variance bitmap A failed to load!");
	Assert(inputvarsA->loadBitmap(inputfile + "_variance_square_A", inputtype), "Input variance square bitmap A failed to load!");
	Assert(inputB->loadBitmap(inputfile + "_B", inputtype), "Input bitmap B failed to load!");
	Assert(inputsppB->loadBitmap(inputfile + "_spp_B", inputtype), "Input spp bitmap B failed to load!");
	Assert(inputvarsB->loadBitmap(inputfile + "_variance_square_B", inputtype), "Input variance square bitmap B failed to load!");
	Assert(inputvarB->loadBitmap(inputfile + "_variance_B", inputtype), "Input variance bitmap B failed to load!");

	DenoiserInput<I> *dInput = new DenoiserInput<I>(outputfile);
	dInput->addImageBlock(new TImageBlock<I>(Point2i(0., 0.), inputA->getSize(), 1, false, inputA, inputsppA, inputvarA, inputvarsA));
	dInput->addImageBlock(new TImageBlock<I>(Point2i(0., 0.), inputB->getSize(), 1, false, inputB, inputsppB, inputvarB, inputvarsB));
	DenoiserOutput<O> *dOutput = denoiser->denoise(dInput);
	LOG(EInfo, "Denoising finished. Time taken = %d seconds", dOutput->getDenoiseDuration());
	dumpMap(dOutput->getDenoisedImage()->getBitmap(), outputfile, outputtype);
	inputA->unloadBitmap();
	inputsppA->unloadBitmap();
	inputvarA->unloadBitmap();
	inputvarsA->unloadBitmap();
	inputB->unloadBitmap();
	inputsppB->unloadBitmap();
	inputvarB->unloadBitmap();
	inputvarsB->unloadBitmap();
	std::cin.get();
	_CrtDumpMemoryLeaks(); // prints mem leaks
	return 0;
}
Beispiel #6
0
template<typename I, typename O> int denoiseMLTNLMeans(std::string inputfile, EBitmapType inputtype, std::string outputfile, EBitmapType outputtype, int r = 3, int f = 1, Float k = 0.7, Float sigma = 0.1, int numinstances = 1, bool dump = true) {
	MLTNLMeansDenoiser<I, O> *denoiser = new MLTNLMeansDenoiser<I, O>(r, f, k, sigma, numinstances, dump);

	DenoiserInput<I> *dInput = new DenoiserInput<I>(outputfile);
	// load bitmaps into DenoiserInput
	for (int i = 1; i <= numinstances; ++i) {
		TBitmap<I> *inputBitmap = new TBitmap<I> ;
		std::string stri = std::to_string(i);
		Assert(inputBitmap->loadBitmap(inputfile + "_" + stri, inputtype), "Input bitmap no."+ stri +" failed to load!");
		dInput->addImageBlock(new TImageBlock<I>(Point2i(0., 0.), inputBitmap->getSize(), 1, false, inputBitmap));
	}

	DenoiserOutput<O> *dOutput = denoiser->denoise(dInput);
	LOG(EInfo, "Denoising finished. Time taken = %d seconds", dOutput->getDenoiseDuration());
	dumpMap(dOutput->getDenoisedImage()->getBitmap(), outputfile, outputtype);

	for (int i = 0; i < numinstances; ++i) {
		dInput->getImageBlocks()[i]->getBitmap()->unloadBitmap();
	}
	std::cin.get();
	_CrtDumpMemoryLeaks(); // prints mem leaks
	return 0;
}
Beispiel #7
0
//TODO this whole function can do with extracting whole blocks into functions
int main(int argc, char** argv)
{
	argv;//squash warning
	argc;

//TODO we should flip, and call it USE_DEBUG_MAP
#define REALMAP 1
#if REALMAP

	char scene_dir_path[128];
	elm_zeromem(scene_dir_path, 128);
	elm_get_parent_dir(argv[0], scene_dir_path, 128);
	strcat(scene_dir_path, "/../../tests/external/astar/scen");
	int32 scene_name_buffer_len = 128;
	char** scene_names = (char**)malloc(scene_name_buffer_len*sizeof(char*));
	elm_zeromem(scene_names, scene_name_buffer_len);
	int scenario_count = elm_get_dir_listing(
								scene_dir_path,
								scene_names,
								scene_name_buffer_len
								);
	ELM_ASSERT(scenario_count);

	QueryScenario** scenarios = (QueryScenario**)malloc(scenario_count*sizeof(QueryScenario*));

	for (uint32 scenario_iter = 0; scenario_iter < scenario_count; ++scenario_iter)
	{
		QueryScenario* scenario = (QueryScenario*)malloc(sizeof(QueryScenario));
		scenarios[scenario_iter] = scenario;

		char* scene_path = malloc(128);
		elm_zeromem(scene_path, 128);
		strcpy(scene_path,scene_dir_path);
		strcat(scene_path, "/");
		strcat(scene_path,scene_names[scenario_iter]);
		FILE* sceneFile = fopen(scene_path, "r");
		ELM_ASSERT(sceneFile);
		free(scene_path);

		int lineCount = 0;
		int iter = 0;
		
		while (iter != EOF)
		{
			iter = fgetc(sceneFile);
			if (iter == '\n')
				++lineCount;
		}

		const int nonQueryLines = 1; //one for version
		const int queryCount = lineCount - nonQueryLines;
		MapQuery* queries = (MapQuery*)malloc(queryCount*sizeof(MapQuery));
		scenario->queries = queries;
		scenario->query_count = queryCount;

		rewind(sceneFile);
		//have to skip the first line
		while (fgetc(sceneFile) != '\n');

		char map_name[128];
		int throwawayInt = 0xDEADBEEF;
		for (int i = 0; i < queryCount; ++i)
		{
			fscanf(sceneFile, "%i %s %i %i %i %i %i %i %f\n",
				&throwawayInt,
				map_name,
				&throwawayInt,
				&throwawayInt,
				&queries[i].startX,
				&queries[i].startY,
				&queries[i].endX,
				&queries[i].endY,
				&queries[i].reference
				);

		}

		fclose(sceneFile);

		int32 map_path_buffer_len = 128;
		char* map_path = (char*)malloc(map_path_buffer_len);
		elm_zeromem(map_path, map_path_buffer_len);
		strcpy(map_path, scene_dir_path);
		strcat(map_path, "/../map/");
		strcat(map_path, map_name);

		FILE* mapFile = fopen(map_path, "r");
		if (mapFile == NULL)
		{
			printf("invalid map file %s", map_path);
			return 1;
		}

		//handle header
		int32 width = 0;
		int32 height = 0;
		while (fgetc(sceneFile) != '\n');
		fscanf(mapFile, "height %i\n", &height);
		fscanf(mapFile, "width %i\n", &width);
		while (fgetc(sceneFile) != '\n');


		elm_astar_map* map = elm_astar_create_map((int16)width, (int16)height);
		for (int j = 0; j < height; ++j)
		{
			for (int i = 0; i < width; ++i)
				map->data[i + j*width] = getc(mapFile) == '.' ? 0 : 1;
			getc(mapFile);
		}
		fclose(mapFile);
		scenario->map = map;
	}

	//TODO no!
	scenario_count = 1;
	for (uint32 scenario_iter = 0; scenario_iter < scenario_count; ++scenario_iter)
	{
		QueryScenario* scenario = scenarios[scenario_iter];
		printf("starting scenario %d, %d queries\n", scenario_iter, scenario->query_count);

		for (int i = 0; i < scenario->query_count; ++i)
		{
			uint16 outBuffer[0x1000];

	ELM_BENCHMARK(
				elm_astar_classic(
				scenario->map,
				(uint16)scenario->queries[i].startX, 
				(uint16)scenario->queries[i].startY,
				(uint16)scenario->queries[i].endX,
				(uint16)scenario->queries[i].endY,
				outBuffer, 0x1000
				);
			);
			
#if ELM_ASTAR_TRACE
			char outname[256];
			sprintf(outname, "map_%04d.png", i);
			dumpMap(scenario->map, outname);
			//clear the dbg data from the map
			for (int32 p = 0; p < scenario->map->width*scenario->map->height; ++p)
				scenario->map->data[p] = scenario->map->data[p] == 1 ? 1 : 0;
#endif
		}
	}
pair<DOMPatchSupport::ResultMap, DOMPatchSupport::ResultMap>
DOMPatchSupport::diff(const Vector<OwnPtr<Digest> >& oldList, const Vector<OwnPtr<Digest> >& newList)
{
    ResultMap newMap(newList.size());
    ResultMap oldMap(oldList.size());

    for (size_t i = 0; i < oldMap.size(); ++i) {
        oldMap[i].first = 0;
        oldMap[i].second = 0;
    }

    for (size_t i = 0; i < newMap.size(); ++i) {
        newMap[i].first = 0;
        newMap[i].second = 0;
    }

    // Trim head and tail.
    for (size_t i = 0; i < oldList.size() && i < newList.size() && oldList[i]->m_sha1 == newList[i]->m_sha1; ++i) {
        oldMap[i].first = oldList[i].get();
        oldMap[i].second = i;
        newMap[i].first = newList[i].get();
        newMap[i].second = i;
    }
    for (size_t i = 0; i < oldList.size() && i < newList.size() && oldList[oldList.size() - i - 1]->m_sha1 == newList[newList.size() - i - 1]->m_sha1; ++i) {
        size_t oldIndex = oldList.size() - i - 1;
        size_t newIndex = newList.size() - i - 1;
        oldMap[oldIndex].first = oldList[oldIndex].get();
        oldMap[oldIndex].second = newIndex;
        newMap[newIndex].first = newList[newIndex].get();
        newMap[newIndex].second = oldIndex;
    }

    typedef HashMap<String, Vector<size_t> > DiffTable;
    DiffTable newTable;
    DiffTable oldTable;

    for (size_t i = 0; i < newList.size(); ++i) {
        newTable.add(newList[i]->m_sha1, Vector<size_t>()).storedValue->value.append(i);
    }

    for (size_t i = 0; i < oldList.size(); ++i) {
        oldTable.add(oldList[i]->m_sha1, Vector<size_t>()).storedValue->value.append(i);
    }

    for (DiffTable::iterator newIt = newTable.begin(); newIt != newTable.end(); ++newIt) {
        if (newIt->value.size() != 1)
            continue;

        DiffTable::iterator oldIt = oldTable.find(newIt->key);
        if (oldIt == oldTable.end() || oldIt->value.size() != 1)
            continue;

        newMap[newIt->value[0]] = std::make_pair(newList[newIt->value[0]].get(), oldIt->value[0]);
        oldMap[oldIt->value[0]] = std::make_pair(oldList[oldIt->value[0]].get(), newIt->value[0]);
    }

    for (size_t i = 0; newList.size() > 0 && i < newList.size() - 1; ++i) {
        if (!newMap[i].first || newMap[i + 1].first)
            continue;

        size_t j = newMap[i].second + 1;
        if (j < oldMap.size() && !oldMap[j].first && newList[i + 1]->m_sha1 == oldList[j]->m_sha1) {
            newMap[i + 1] = std::make_pair(newList[i + 1].get(), j);
            oldMap[j] = std::make_pair(oldList[j].get(), i + 1);
        }
    }

    for (size_t i = newList.size() - 1; newList.size() > 0 && i > 0; --i) {
        if (!newMap[i].first || newMap[i - 1].first || newMap[i].second <= 0)
            continue;

        size_t j = newMap[i].second - 1;
        if (!oldMap[j].first && newList[i - 1]->m_sha1 == oldList[j]->m_sha1) {
            newMap[i - 1] = std::make_pair(newList[i - 1].get(), j);
            oldMap[j] = std::make_pair(oldList[j].get(), i - 1);
        }
    }

#ifdef DEBUG_DOM_PATCH_SUPPORT
    dumpMap(oldMap, "OLD");
    dumpMap(newMap, "NEW");
#endif

    return std::make_pair(oldMap, newMap);
}
Beispiel #9
0
int main(int argc, char *argv[])
{
  if (argc < 4){
    printf( "Usage: %s <servicename> <directory>|<definition_file> <REQUEST> [<functionname> <param_1>[...<param_n>]]\n", basename(argv[0]) );
    return 1;
  }
 
  map* outputs=NULL;
  /**
   * Parsing inputs (need a loop over all files in the service path !!)
   */
  maps* m;
  m=(maps*)malloc(MAP_SIZE);
  conf_read("main.cfg",m);
  map* tmpm=getMapFromMaps(m,"main","serverAddress");
  int toto=count(tmpm);
  //printf(" - %i \n",toto);

  if(tmpm!=NULL)
    SERVICE_URL=strdup(tmpm->value);
  else
    SERVICE_URL=DEFAULT_SERVICE_URL;

  service* s[100];
  service* s1;
  int scount=0;

  if(strcmp(argv[3],"GetCapabilities")==0){
    int i=0;
    struct dirent *dp;
    DIR *dirp = opendir(argv[1]);
    int t;
    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
    xmlNodePtr n = printGetCapabilitiesHeader(doc,argv[2],m);
    
    int saved_stdout = dup(fileno(stdout));
    stdout = freopen("/dev/null" , "w" , stdout);
    while ((dp = readdir(dirp)) != NULL)
      if(strstr(dp->d_name,".zcfg")!=0){
	char toto1[1024];
	sprintf(toto1,"%s%s",argv[1],dp->d_name);
	char *toto=toto1;
	s1=(service*)malloc(sizeof(char*)+(MAP_SIZE*2)+(2*ELEMENTS_SIZE));
	//s[scount]=(service*)malloc(sizeof(service*));
	//#ifdef DEBUG
	fprintf(stderr,"#################\n%s\n#################\n",toto1);
	//printf("|(1)");
	//#endif
	t=getServiceFromFile(toto1,&s1);
	
	//printf("|(2)");
	printGetCapabilitiesForProcess(m,n,s1);
	/**
	 * Valgrind told us that there is an issue regarding a 
	 * "conditional jump or move depends on uninitialised value(s)" for
	 * freeIOType
	 */
	//freeService(&s1);
	scount++;
      }
    char buf[20];
    sprintf(buf, "/dev/fd/%d", saved_stdout);
    stdout = freopen(buf , "w" , stdout);

    printDocument(doc);
    fflush(stdout);
    free(m);
    return 0;
  }
  else{
    s1=(service*)malloc(sizeof(char*)+(MAP_SIZE*2)+(2*ELEMENTS_SIZE));
    //s[0]=(service*)malloc(sizeof(service*));
    int t=getServiceFromFile(argv[1],&s1);
    if(strcmp(argv[3],"DescribeProcess")==0){
      printDescribeProcessResponse(s1,argv[2]);
      //dumpMaps(m);
      //free(s1);
      return 0;
    }
    else
      if(strcmp(argv[3],"Execute")!=0){
	fprintf(stderr,"");
	//free(s);
	return 0;
      }
  }
  //dumpService(s);
  s[0]=s1;
  map* inputs=NULL;
  elements* c_inputs=s1->inputs;
  int j;
  for(j=0;j<argc-5;j++){
    //dumpElements(c_inputs);
    if(inputs!=NULL)
      addToMap(inputs,c_inputs->name,argv[j+5]);
    else
      inputs=createMap(c_inputs->name,argv[j+5]);
    if(c_inputs->next!=NULL || j+1>=argc-5)
      c_inputs=c_inputs->next;
    else{
      map* tmps=createMap("text","ERROR you provided more inputs than requested.");
      printExceptionReportResponse(m,tmps);
      //printf("ERROR you provided more inputs than requested.");
      return -1;
    }
#ifdef DEBUG
    printf("ARGV1 %d %s\n",j,inputs->value);
#endif
  }

#ifdef DEBUG
  dumpMap(inputs);
#endif

  const struct tm *tm;
  size_t len;
  time_t now;
  char *sDate;
  
  now = time ( NULL );
  tm = localtime ( &now );

  sDate = new char[TIME_SIZE];

  len = strftime ( sDate, TIME_SIZE, "%d-%B-%YT%I:%M:%SZ", tm );

#ifdef DEBUG
  printf("Trying to load %s\n", argv[2]);
#endif
  void* so = dlopen(argv[2], RTLD_LAZY);
  char *errstr;
  errstr = dlerror();
  if( so != NULL ) {
    typedef int (*execute_t)(map**,map**);
#ifdef DEBUG
    printf("Library loaded %s \n",errstr);
#endif
    execute_t execute=(execute_t)dlsym(so,argv[4]);
#ifdef DEBUG
    errstr = dlerror();
    printf("Function loaded %s\n",errstr);
#endif	

    /**
     * Need to check if we need to fork to load a status enabled 
     */
    char _toto[10];
    sprintf(_toto,"input_%i",argc-5);
    map* toto=getMap(inputs,_toto);
    if(strcmp(argv[argc-1],"bg")!=0){
#ifdef DEBUG
      printf("RUN IN NORMAL MODE \n");
#endif
      int res=execute(&inputs,&outputs);
#ifdef DEBUG
      printf("RUNNED IN NORMAL MODE \n");
      dumpMap(inputs);
      dumpMap(outputs);
#endif
      printProcessResponse(m,getpid(),s[0],argv[2],res,inputs,outputs);
    }
    else{
      pid_t   pid;
      int cpid=getpid();
      pid = fork ();
      if (pid > 0) {
	/**
	 * dady :
	 * set status to SERVICE_ACCEPTED
	 */
	printProcessResponse(m,pid,s[0],argv[2],SERVICE_ACCEPTED,inputs,outputs);
      }else if (pid == 0) {
	/* son */
	if (signal(SIGINT, sigint_handler) == SIG_ERR) {
	  printf("signal");
	  map* tmps=createMap("text","father received sigint.");
	  printExceptionReportResponse(m,tmps);
	  exit(1);
	}
#ifdef DEBUG
	printf("RUN IN BACKGROUND MODE \n");
#endif
	char tmp1[256];
	sprintf(tmp1,"service/temp/%s_%d.xml",argv[2],getpid());
	stdout = freopen(tmp1 , "w+" , stdout);
	/**
	 * set status to SERVICE_STARTED
	 */
	printProcessResponse(m,getpid(),s[0],argv[2],SERVICE_STARTED,inputs,outputs);
	fflush(stdout);
	rewind(stdout);
	int t=execute(&inputs,&outputs);
	/**
	 * set status to status code returned by the service function
	 */
	printProcessResponse(m,getpid(),s[0],argv[2],t,inputs,outputs);
      } else {
	/* error */
      }
    }
#ifdef DEBUG
    errstr = dlerror();
    printf("Function successfully loaded %s, unloading now.\n",errstr);
#endif
    dlclose(so);
  }
  else {
#ifdef DEBUG
    printf("C Library can't be loaded %s \n",errstr);
#endif
    python_support(m,s[0],argc,argv,inputs,outputs);
  }
  return 0;
}
Beispiel #10
0
int getServiceFromYAML(maps* conf, char* file,service** service,char *name){
  FILE *fh = fopen("test.yml", "r");
  if(current_content!=NULL){
    freeMap(&current_content);
    free(current_content);
    current_content=NULL;
  }
#ifdef DEBUG_SERVICE_CONF
  fprintf(stderr,"(STARTING)FREE current_element\n");
#endif
  if(current_element!=NULL){
    freeElements(&current_element);
    free(current_element);
    current_element=NULL;
  }
  my_service=NULL;
  
  my_service=*service;
  my_service->name=strdup(name);
  my_service->content=NULL;
  my_service->metadata=NULL;
  my_service->inputs=NULL;
  my_service->outputs=NULL;
  fh = fopen(file,"r");
  if (fh==NULL){
    fprintf(stderr,"error : file not found\n") ;
    return -1;
  }
  yaml_parser_t parser;
  yaml_token_t  token;   /* new variable */

  /* Initialize parser */
  if(!yaml_parser_initialize(&parser))
    fputs("Failed to initialize parser!\n", stderr);
  if(fh == NULL)
    fputs("Failed to open file!\n", stderr);
  /* Set input file */
  yaml_parser_set_input_file(&parser, fh);
  /* BEGIN new code */
  int level=0;
  int plevel=level;
  int ilevel=-1;
  int blevel=-1;
  int ttype=0;
  int wait_metadata=-1;
  char *cur_key;
  do {
    yaml_parser_scan(&parser, &token);
    switch(token.type)
    {
    /* Stream start/end */
    case YAML_STREAM_START_TOKEN: 
#ifdef DEBUG_YAML
      puts("STREAM START"); 
#endif
      break;
    case YAML_STREAM_END_TOKEN:   
#ifdef DEBUG_YAML
      puts("STREAM END");   
#endif
      break;
    /* Token types (read before actual token) */
    case YAML_KEY_TOKEN:   
#ifdef DEBUG_YAML
      printf("(Key token)   "); 
#endif
      ttype=0;
      break;
    case YAML_VALUE_TOKEN: 
#ifdef DEBUG_YAML
      printf("(Value token) "); 
#endif
      ttype=1;
      break;
    /* Block delimeters */
    case YAML_BLOCK_SEQUENCE_START_TOKEN: 
#ifdef DEBUG_YAML
      puts("<b>Start Block (Sequence)</b>"); 
#endif
      break;
    case YAML_BLOCK_ENTRY_TOKEN:          
#ifdef DEBUG_YAML
      puts("<b>Start Block (Entry)</b>");    
#endif
      break;
    case YAML_BLOCK_END_TOKEN:      
      blevel--;
      if(ilevel>=0)
	ilevel--;
#ifdef DEBUG_YAML
      printf("<b>End block</b> (%d,%d,%d,%d)\n", blevel,level,ilevel,ttype); 
#endif
      break;
    /* Data */
    case YAML_BLOCK_MAPPING_START_TOKEN:  
#ifdef DEBUG_YAML
      puts("[Block mapping]");            
#endif
      blevel++;
      break;
    case YAML_SCALAR_TOKEN:  
      if(ttype==0){
	cur_key=zStrdup((char *)token.data.scalar.value);
      }
      if(ttype==1){
	if(current_content==NULL){
	  current_content=createMap(cur_key,(char *)token.data.scalar.value);
	}else{
	  addToMap(current_content,cur_key,(char *)token.data.scalar.value);
	}
	free(cur_key);
	cur_key=NULL;
      }

      if(ttype==0 && blevel==0 && level==0 && strcasecmp((char *)token.data.scalar.value,"MetaData")==0 && blevel==0){
	addMapToMap(&my_service->content,current_content);
#ifdef DEBUG_YAML
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=1;
      }
      if(ttype==0 && blevel>0 && level>0 && strcasecmp((char *)token.data.scalar.value,"MetaData")==0){
	if(current_element->content==NULL && current_content!=NULL)
	  addMapToMap(&current_element->content,current_content);
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=1;
      }
      if(ttype==0 && strcasecmp((char *)token.data.scalar.value,"inputs")==0 && blevel==0){
	if(wait_metadata>0){
	  addMapToMap(&my_service->metadata,current_content);
	  wait_metadata=-1;
	}else{
	  if(current_content!=NULL && my_service->content==NULL)
	    addMapToMap(&my_service->content,current_content);
	}
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=false;
	level++;
      }
      if(ttype==0 && strcasecmp((char *)token.data.scalar.value,"outputs")==0 && blevel==1){
	level++;
#ifdef DEBUG_YAML
	dumpMap(current_content);
	printf("\n***\n%d (%d,%d,%d,%d)\n+++\n", current_element->defaults==NULL,blevel,level,ilevel,ttype); 
#endif
	if(current_element->defaults==NULL && current_content!=NULL && ilevel<0){
	  current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	  current_element->defaults->content=NULL;
	  current_element->defaults->next=NULL;
	  addMapToMap(&current_element->defaults->content,current_content);
#ifdef DEBUG_YAML
	  dumpElements(current_element);
	  dumpMap(current_content);
	  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	  freeMap(&current_content);
	  free(current_content);
	  current_content=NULL;
	}else{
	  if(current_content!=NULL && ilevel<=0){
	    addMapToIoType(&current_element->supported,current_content);
#ifdef DEBUG_YAML
	    dumpElements(current_element);
	    dumpMap(current_content);
	    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	    freeMap(&current_content);
	    free(current_content);
	    current_content=NULL;
	  }
	}
      }
      if(level==1 && strcasecmp((char *)token.data.scalar.value,"default")==0){
	ilevel=0;
      }
      if(level==1 && strcasecmp((char *)token.data.scalar.value,"supported")==0){
#ifdef DEBUG_YAML
	dumpMap(current_content);
	printf("\n***\n%d (%d,%d,%d,%d)\n+++\n", current_element->defaults==NULL,blevel,level,ilevel,ttype); 
#endif
	if(current_element->defaults==NULL && current_content!=NULL && ilevel<0){
	  current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	  current_element->defaults->content=NULL;
	  current_element->defaults->next=NULL;
	  addMapToMap(&current_element->defaults->content,current_content);
#ifdef DEBUG_YAML
	  dumpElements(current_element);
	  dumpMap(current_content);
	  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	  freeMap(&current_content);
	  free(current_content);
	  current_content=NULL;
	}else{
	  if(current_content!=NULL && ilevel<=0){
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	    }
	    addMapToMap(&current_element->supported->content,current_content);
#ifdef DEBUG_YAML
	    dumpElements(current_element);
	    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	    freeMap(&current_content);
	    free(current_content);
	    current_content=NULL;
	  }
	}
	ilevel=1;
      }


      if(strncasecmp((char *)token.data.scalar.value,"ComplexData",11)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"LiteralData",10)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"ComplexOutput",13)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"LiteralOutput",12)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"BoundingBoxOutput",13)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"BoundingBoxData",12)==0){
	current_element->format=zStrdup((char *)token.data.scalar.value);
	free(cur_key);
	cur_key=NULL;
	if(wait_metadata>0 && current_content!=NULL){
	  addMapToMap(&current_element->metadata,current_content);
	  wait_metadata=-1;
	}else{
	  if(current_content!=NULL){
	    addMapToMap(&current_element->content,current_content);
	  }
	}
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
#ifdef DEBUG_YAML
	dumpElements(current_element);
#endif
      }

      if(blevel==1 && level==1){
	if(current_element!=NULL && current_content!=NULL){
	  if(current_element->defaults==NULL){
	    current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	    current_element->defaults->content=NULL;
	    current_element->defaults->next=NULL;
	    addMapToMap(&current_element->defaults->content,current_content);
	  }else{
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	      addMapToMap(&current_element->supported->content,current_content);
	    }else
	      addMapToIoType(&current_element->supported,current_content);
	  }
	}
	if(current_element!=NULL){
	  if(my_service->inputs==NULL)
	    my_service->inputs=dupElements(current_element);
	  else
	    addToElements(&my_service->inputs,current_element);
	  freeElements(&current_element);
	  free(current_element);
	}
	plevel=level;
	current_element=(elements*)malloc(ELEMENTS_SIZE);
	current_element->name=zStrdup((char *)token.data.scalar.value);
	current_element->content=NULL;
	current_element->metadata=NULL;
	current_element->format=NULL;
	current_element->defaults=NULL;
	current_element->supported=NULL;
	current_element->next=NULL;
	
      }
      if(blevel==1 && level==2){
	if(current_element!=NULL && current_content!=NULL){
	  if(current_element->defaults==NULL){
	    current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	    current_element->defaults->content=NULL;
	    current_element->defaults->next=NULL;
	    addMapToMap(&current_element->defaults->content,current_content);
	  }else{
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	      addMapToMap(&current_element->supported->content,current_content);
	    }else
	      addMapToIoType(&current_element->supported,current_content);
	  }
	}
	if(current_element!=NULL){
	  if(plevel==level){
	    if(my_service->outputs==NULL)
	      my_service->outputs=dupElements(current_element);
	    else
	      addToElements(&my_service->outputs,current_element);
	  }else{
	    if(my_service->inputs==NULL)
	      my_service->inputs=dupElements(current_element);
	    else
	      addToElements(&my_service->inputs,current_element);
	  }
	  freeElements(&current_element);
	  free(current_element);
	}
	plevel=level;
	current_element=(elements*)malloc(ELEMENTS_SIZE);
	current_element->name=zStrdup((char *)token.data.scalar.value);
	current_element->content=NULL;
	current_element->metadata=NULL;
	current_element->format=NULL;
	current_element->defaults=NULL;
	current_element->supported=NULL;
	current_element->next=NULL;
	
      }


#ifdef DEBUG_YAML
      printf("scalar %s (%d,%d,%d,%d,%d)\n", token.data.scalar.value,blevel,level,plevel,ilevel,ttype); 
#endif
      break;
    /* Others */
    default:
      if(token.type==0){
	char tmp[1024];
	sprintf(tmp,"Wrong charater found in %s: \\t",name);
	setMapInMaps(conf,"lenv","message",tmp);
	return -1;
      }
#ifdef DEBUG_YAML
      printf("Got token of type %d\n", token.type);
#endif
      break;
    }
    if(token.type != YAML_STREAM_END_TOKEN )
      yaml_token_delete(&token);
  } while(token.type != YAML_STREAM_END_TOKEN);
  yaml_token_delete(&token);


#ifdef DEBUG_YAML
  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
  if(current_element!=NULL && current_content!=NULL){
    if(current_element->defaults==NULL){
      current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
      current_element->defaults->content=NULL;
      current_element->defaults->next=NULL;
      addMapToMap(&current_element->defaults->content,current_content);
    }else{
      if(current_element->supported==NULL){
	current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	current_element->supported->content=NULL;
	current_element->supported->next=NULL;
	addMapToMap(&current_element->supported->content,current_content);
      }else
	addMapToIoType(&current_element->supported,current_content);
    }
#ifdef DEBUG_YAML
    dumpMap(current_content);
    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
    freeMap(&current_content);
    free(current_content);
    current_content=NULL;
  }
  if(current_element!=NULL){
    if(my_service->outputs==NULL)
      my_service->outputs=dupElements(current_element);
    else
      addToElements(&my_service->outputs,current_element);
    freeElements(&current_element);
    free(current_element);
    current_element=NULL;
  }
  /* END new code */

  /* Cleanup */
  yaml_parser_delete(&parser);
  fclose(fh);

#ifdef DEBUG_YAML
  dumpService(my_service);
#endif
  *service=my_service;

  return 1;
}
Beispiel #11
0
static void *
upnpNatpmpThread( )
{
	int oldStatus, newStatus;
	int i, err;
	time_t now;
	struct timespec deltatime;

	pthread_mutex_lock(&g_mutex);
	g_stop = 0;
	pthread_mutex_unlock(&g_mutex);

	while( g_running ){
		//clear in g_unmaps
		now = time(NULL);
		for(i = 0; i < MAX_MAPS; i++){
			if ( ! g_running )	break;

			if ( ! g_unmaps[i].enabled && g_unmaps[i].extPort > 0 ){
				if ( g_unmaps[i].overTime < now ){
					oldStatus = getStatus( &g_unmaps[i] );

					pthread_mutex_lock(&g_mutex);

					switch (oldStatus){
			        case ML_PORT_MAPPED:
			        	g_unmaps[i].overTime = now + 60 * 20;
			        	break;
			        case ML_PORT_ERROR:
			        	g_unmaps[i].overTime = now + 60;
			        	break;
			        default:
			            /* in progress.  pulse frequently. */
			        	g_unmaps[i].overTime = now + 333;
			            break;
					}
					g_unmaps[i].natpmpStatus = natpmpPulse( &g_unmaps[i] );
					g_unmaps[i].doPortCheck = 0;
					g_unmaps[i].upnpStatus  = upnpPulse( &g_unmaps[i]);
					dbg_printf( "upnpNatpmpThread g_unmaps[%d]\n", i);

#ifdef DEBUG_PRINTF_UPNP
					dumpMap(&g_unmaps[i], 1);
#endif
					newStatus    = getStatus( &g_unmaps[i] );

					if( newStatus != oldStatus )
						dbg_printf( "port forwarding state changed from \"%s\" to \"%s\"\n", getNatStateStr( oldStatus ),	getNatStateStr( newStatus ) );
					if( newStatus == ML_PORT_UNMAPPED ){
						memset(&g_unmaps[i], 0, sizeof(ml_upnpmp_t));
					}
					pthread_mutex_unlock(&g_mutex);
				}
			}
		}
		//create,check in g_maps
		now = time(NULL);
		for(i = 0; i < MAX_MAPS; i++){
			if ( ! g_running )	break;

			if ( g_maps[i].enabled && g_maps[i].extPort ){
				if ( g_maps[i].overTime < now ){
					oldStatus = getStatus( &g_maps[i] );

					pthread_mutex_lock(&g_mutex);

					switch (oldStatus){
			        case ML_PORT_MAPPED:
			        	g_maps[i].overTime = now + 60 * 20;
			        	break;
			        case ML_PORT_ERROR:
			        	g_maps[i].overTime = now + 60;
			        	break;
			        default:
			            /* in progress.  pulse frequently. */
			        	g_maps[i].overTime = now + 333;
			            break;
					}
					g_maps[i].natpmpStatus = natpmpPulse( &g_maps[i] );
					g_maps[i].doPortCheck = 1;
					g_maps[i].upnpStatus   = upnpPulse( &g_maps[i] );

					pthread_mutex_unlock(&g_mutex);

					dbg_printf( "upnpNatpmpThread g_maps[%d]\n", i);
#ifdef DEBUG_PRINTF_UPNP
					dumpMap(&g_maps[i], 1);
#endif

					newStatus = getStatus( &g_maps[i] );

					if( newStatus != oldStatus )
						dbg_printf( "port forwarding state changed from \"%s\" to \"%s\"\n", getNatStateStr( oldStatus ), getNatStateStr( newStatus ) );
				}
			}
		}
		if ( g_running ){
			deltatime.tv_sec = time(NULL) + 30;
			deltatime.tv_nsec = 0;
#if defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS - 200112L) >= 0L
			err = pthread_mutex_timedlock(&g_delay_mutex, &deltatime);
			dbg_printf("%d seconds timedlock err=%d, running...\n", deltatime.tv_sec, err);
#else
			do {
				err = pthread_mutex_trylock(&g_delay_mutex);
				if(err == EBUSY){
					struct timespec ts;
					ts.tv_sec = 0;
					ts.tv_nsec = 100000000;
					int status = -1;
					while (status == -1) status = nanosleep(&ts, &ts);
				} else break;
				//dbg_printf("trylock err=%d, running...\n", err);
			} while (err != 0 && (time(NULL) < deltatime.tv_sec));
#endif
		}else{
			break;
		}
	}
	pthread_mutex_lock(&g_mutex);
	g_stop = 1;
	pthread_mutex_unlock(&g_mutex);
	dbg_printf("upnp thread stopped!\n");

	return NULL;
}