Beispiel #1
0
/**
 * @brief The entry point of NAEV.
 *
 *    @param[in] argc Number of arguments.
 *    @param[in] argv Array of argc arguments.
 *    @return EXIT_SUCCESS on success.
 */
int main( int argc, char** argv )
{
   char buf[PATH_MAX];

   /* Save the binary path. */
   binary_path = argv[0];
   
   /* Print the version */
   LOG( " "APPNAME" v%s", naev_version(0) );
#ifdef GIT_COMMIT
   DEBUG( " git HEAD at " GIT_COMMIT );
#endif /* GIT_COMMIT */

   /* Initializes SDL for possible warnings. */
   SDL_Init(0);

   /* Set up debug signal handlers. */
   debug_sigInit();

   /* Create the home directory if needed. */
   if (nfile_dirMakeExist("%s", nfile_basePath()))
      WARN("Unable to create naev directory '%s'", nfile_basePath());

   /* Must be initialized before input_init is called. */
   if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
      WARN("Unable to initialize SDL Video: %s", SDL_GetError());
      return -1;
   }

   /* Get desktop dimensions. */
#if SDL_VERSION_ATLEAST(1,2,10)
   const SDL_VideoInfo *vidinfo = SDL_GetVideoInfo();
   gl_screen.desktop_w = vidinfo->current_w;
   gl_screen.desktop_h = vidinfo->current_h;
#else /* #elif SDL_VERSION_ATLEAST(1,2,10) */
   gl_screen.desktop_w = 0;
   gl_screen.desktop_h = 0;
#endif /* #elif SDL_VERSION_ATLEAST(1,2,10) */

   /* We'll be parsing XML. */
   LIBXML_TEST_VERSION
   xmlInitParser();

   /* Input must be initialized for config to work. */
   input_init(); 

   /* Set the configuration. */
   snprintf(buf, PATH_MAX, "%s"CONF_FILE, nfile_basePath());
   conf_setDefaults(); /* set the default config values */
   conf_loadConfig(buf); /* Lua to parse the configuration file */
   conf_parseCLI( argc, argv ); /* parse CLI arguments */

   /* Enable FPU exceptions. */
#if !(HAS_WIN32) && defined(DEBUGGING)
   if (conf.fpu_except)
      feenableexcept( FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW );
#endif /* DEBUGGING */

   /* Open data. */
   if (ndata_open() != 0)
      ERR("Failed to open ndata.");

   /* Load the data basics. */
   LOG(" %s", ndata_name());
   DEBUG();

   /* Display the SDL Version. */
   print_SDLversion();
   DEBUG();

   /* random numbers */
   rng_init();


   /*
    * OpenGL
    */
   if (gl_init()) { /* initializes video output */
      ERR("Initializing video output failed, exiting...");
      SDL_Quit();
      exit(EXIT_FAILURE);
   }
   window_caption();
   gl_fontInit( NULL, NULL, FONT_SIZE ); /* initializes default font to size */
   gl_fontInit( &gl_smallFont, NULL, FONT_SIZE_SMALL ); /* small font */

   /* Display the load screen. */
   loadscreen_load();
   loadscreen_render( 0., "Initializing subsystems..." );
   time = SDL_GetTicks();


   /*
    * Input
    */
   if ((conf.joystick_ind >= 0) || (conf.joystick_nam != NULL)) {
      if (joystick_init()) WARN("Error initializing joystick input");
      if (conf.joystick_nam != NULL) { /* use the joystick name to find a joystick */
         if (joystick_use(joystick_get(conf.joystick_nam))) {
            WARN("Failure to open any joystick, falling back to default keybinds");
            input_setDefault();
         }
         free(conf.joystick_nam);
      }
      else if (conf.joystick_ind >= 0) /* use a joystick id instead */
         if (joystick_use(conf.joystick_ind)) {
            WARN("Failure to open any joystick, falling back to default keybinds");
            input_setDefault();
         }
   }


   /*
    * OpenAL - Sound
    */
   if (conf.nosound) {
      LOG("Sound is disabled!");
      sound_disabled = 1;
      music_disabled = 1;
   }
   if (sound_init()) WARN("Problem setting up sound!");
   music_choose("load");


   /* Misc graphics init */
   if (nebu_init() != 0) { /* Initializes the nebula */
      /* An error has happened */
      ERR("Unable to initialize the Nebula subsystem!");
      /* Weirdness will occur... */
   }
   gui_init(); /* initializes the GUI graphics */
   toolkit_init(); /* initializes the toolkit */
   map_init(); /* initializes the map. */
   cond_init(); /* Initialize conditional subsystem. */

   /* Data loading */
   load_all();

   /* Unload load screen. */
   loadscreen_unload();

   /* Start menu. */
   menu_main();

   /* Force a minimum delay with loading screen */
   if ((SDL_GetTicks() - time) < NAEV_INIT_DELAY)
      SDL_Delay( NAEV_INIT_DELAY - (SDL_GetTicks() - time) );
   time = SDL_GetTicks(); /* initializes the time */
   /* 
    * main loop
    */
   SDL_Event event;
   /* flushes the event loop since I noticed that when the joystick is loaded it
    * creates button events that results in the player starting out acceling */
   while (SDL_PollEvent(&event));
   /* primary loop */
   while (!quit) {
      while (SDL_PollEvent(&event)) { /* event loop */
         if (event.type == SDL_QUIT)
            quit = 1; /* quit is handled here */

         input_handle(&event); /* handles all the events and player keybinds */
      }

      main_loop();
   }


   /* Save configuration. */
   conf_saveConfig(buf);

   /* cleanup some stuff */
   player_cleanup(); /* cleans up the player stuff */
   gui_free(); /* cleans up the player's GUI */
   weapon_exit(); /* destroys all active weapons */
   pilots_free(); /* frees the pilots, they were locked up :( */
   cond_exit(); /* destroy conditional subsystem. */
   land_exit(); /* Destroys landing vbo and friends. */

   /* data unloading */
   unload_all();

   /* cleanup opengl fonts */
   gl_freeFont(NULL);
   gl_freeFont(&gl_smallFont);

   /* Close data. */
   ndata_close();

   /* Destroy conf. */
   conf_cleanup(); /* Frees some memory the configuration allocated. */

   /* exit subsystems */
   map_exit(); /* destroys the map. */
   toolkit_exit(); /* kills the toolkit */
   ai_exit(); /* stops the Lua AI magic */
   joystick_exit(); /* releases joystick */
   input_exit(); /* cleans up keybindings */
   nebu_exit(); /* destroys the nebula */
   gl_exit(); /* kills video output */
   sound_exit(); /* kills the sound */
   news_exit(); /* destroys the news. */

   /* Free the icon. */
   if (naev_icon)
      free(naev_icon);

   SDL_Quit(); /* quits SDL */

   /* all is well */
   exit(EXIT_SUCCESS);
}
Beispiel #2
0
/**
 * @brief The entry point of Naev.
 *
 *    @param[in] argc Number of arguments.
 *    @param[in] argv Array of argc arguments.
 *    @return EXIT_SUCCESS on success.
 */
int main( int argc, char** argv )
{
   char buf[PATH_MAX];

   /* Save the binary path. */
   binary_path = strdup(argv[0]);

   /* Print the version */
   LOG( " "APPNAME" v%s", naev_version(0) );
#ifdef GIT_COMMIT
   DEBUG( " git HEAD at " GIT_COMMIT );
#endif /* GIT_COMMIT */

   /* Initializes SDL for possible warnings. */
   SDL_Init(0);

   /* Initialize the threadpool */
   threadpool_init();

   /* Set up debug signal handlers. */
   debug_sigInit();

   /* Must be initialized before input_init is called. */
   if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
      WARN("Unable to initialize SDL Video: %s", SDL_GetError());
      return -1;
   }

   /* Get desktop dimensions. */
#if SDL_VERSION_ATLEAST(1,2,10)
   const SDL_VideoInfo *vidinfo = SDL_GetVideoInfo();
   gl_screen.desktop_w = vidinfo->current_w;
   gl_screen.desktop_h = vidinfo->current_h;
#else /* #elif SDL_VERSION_ATLEAST(1,2,10) */
   gl_screen.desktop_w = 0;
   gl_screen.desktop_h = 0;
#endif /* #elif SDL_VERSION_ATLEAST(1,2,10) */

   /* We'll be parsing XML. */
   LIBXML_TEST_VERSION
   xmlInitParser();

   /* Input must be initialized for config to work. */
   input_init();

   conf_setDefaults(); /* set the default config values */

   /*
    * Attempts to load the data path from datapath.lua
    * At this early point in the load process, the binary path
    * is the only place likely to be checked.
    */
   conf_loadConfigPath();

   /* Parse the user data path override first. */
   conf_parseCLIPath( argc, argv );

   /* Create the home directory if needed. */
   if (nfile_dirMakeExist("%s", nfile_configPath()))
      WARN("Unable to create config directory '%s'", nfile_configPath());

   /* Set the configuration. */
   nsnprintf(buf, PATH_MAX, "%s"CONF_FILE, nfile_configPath());

#if HAS_UNIX
   /* TODO get rid of this cruft ASAP. */
   int oldconfig = 0;
   if (!nfile_fileExists( buf )) {
      char *home, buf2[PATH_MAX];
      home = SDL_getenv( "HOME" );
      if (home != NULL) {
         nsnprintf( buf2, PATH_MAX, "%s/.naev/"CONF_FILE, home );
         if (nfile_fileExists( buf2 ))
            oldconfig = 1;
      }
   }
#endif /* HAS_UNIX */

   conf_loadConfig(buf); /* Lua to parse the configuration file */
   conf_parseCLI( argc, argv ); /* parse CLI arguments */

   /* Enable FPU exceptions. */
#if defined(HAVE_FEENABLEEXCEPT) && defined(DEBUGGING)
   if (conf.fpu_except)
      feenableexcept( FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW );
#endif /* defined(HAVE_FEENABLEEXCEPT) && defined(DEBUGGING) */

   /* Open data. */
   if (ndata_open() != 0)
      ERR("Failed to open ndata.");

   /* Load the start info. */
   if (start_load())
      ERR("Failed to load module start data.");

   /* Load the data basics. */
   LOG(" %s", ndata_name());
   DEBUG();

   /* Display the SDL Version. */
   print_SDLversion();
   DEBUG();

   /* random numbers */
   rng_init();

   /*
    * OpenGL
    */
   if (gl_init()) { /* initializes video output */
      ERR("Initializing video output failed, exiting...");
      SDL_Quit();
      exit(EXIT_FAILURE);
   }
   window_caption();
   gl_fontInit( NULL, NULL, conf.font_size_def ); /* initializes default font to size */
   gl_fontInit( &gl_smallFont, NULL, conf.font_size_small ); /* small font */

   /* Display the load screen. */
   loadscreen_load();
   loadscreen_render( 0., "Initializing subsystems..." );
   time_ms = SDL_GetTicks();


   /*
    * Input
    */
   if ((conf.joystick_ind >= 0) || (conf.joystick_nam != NULL)) {
      if (joystick_init()) WARN("Error initializing joystick input");
      if (conf.joystick_nam != NULL) { /* use the joystick name to find a joystick */
         if (joystick_use(joystick_get(conf.joystick_nam))) {
            WARN("Failure to open any joystick, falling back to default keybinds");
            input_setDefault();
         }
         free(conf.joystick_nam);
      }
      else if (conf.joystick_ind >= 0) /* use a joystick id instead */
         if (joystick_use(conf.joystick_ind)) {
            WARN("Failure to open any joystick, falling back to default keybinds");
            input_setDefault();
         }
   }


   /*
    * OpenAL - Sound
    */
   if (conf.nosound) {
      LOG("Sound is disabled!");
      sound_disabled = 1;
      music_disabled = 1;
   }
   if (sound_init()) WARN("Problem setting up sound!");
   music_choose("load");

   /* FPS stuff. */
   fps_setPos( 15., (double)(gl_screen.h-15-gl_defFont.h) );

   /* Misc graphics init */
   if (nebu_init() != 0) { /* Initializes the nebula */
      /* An error has happened */
      ERR("Unable to initialize the Nebula subsystem!");
      /* Weirdness will occur... */
   }
   gui_init(); /* initializes the GUI graphics */
   toolkit_init(); /* initializes the toolkit */
   map_init(); /* initializes the map. */
   cond_init(); /* Initialize conditional subsystem. */
   cli_init(); /* Initialize console. */

   /* Data loading */
   load_all();

   /* Generate the CSV. */
   if (conf.devcsv)
      dev_csv();

   /* Unload load screen. */
   loadscreen_unload();

   /* Start menu. */
   menu_main();

   /* Force a minimum delay with loading screen */
   if ((SDL_GetTicks() - time_ms) < NAEV_INIT_DELAY)
      SDL_Delay( NAEV_INIT_DELAY - (SDL_GetTicks() - time_ms) );
   fps_init(); /* initializes the time_ms */

#if HAS_UNIX
   /* Tell the player to migrate their configuration files out of ~/.naev */
   /* TODO get rid of this cruft ASAP. */
   if ((oldconfig) && (!conf.datapath)) {
      char path[PATH_MAX], *script, *home;
      uint32_t scriptsize;
      int ret;

      nsnprintf( path, PATH_MAX, "%s/naev-confupdate.sh", ndata_getDirname() );
      home = SDL_getenv("HOME");
      ret = dialogue_YesNo( "Warning", "Your configuration files are in a deprecated location and must be migrated:\n"
            "   \er%s/.naev/\e0\n\n"
            "The update script can likely be found in your Naev data directory:\n"
            "   \er%s\e0\n\n"
            "Would you like to run it automatically?", home, path );

      /* Try to run the script. */
      if (ret) {
         ret = -1;
         /* Running from ndata. */
         if (ndata_getPath() != NULL) {
            script = ndata_read( "naev-confupdate.sh", &scriptsize );
            if (script != NULL)
               ret = system(script);
         }

         /* Running from laid-out files or ndata_read failed. */
         if ((nfile_fileExists(path)) && (ret == -1)) {
            script = nfile_readFile( (int*)&scriptsize, path );
            if (script != NULL)
               ret = system(script);
         }

         /* We couldn't find the script. */
         if (ret == -1) {
            dialogue_alert( "The update script was not found at:\n\er%s\e0\n\n"
                  "Please locate and run it manually.", path );
         }
         /* Restart, as the script succeeded. */
         else if (!ret) {
            dialogue_msg( "Update Completed",
                  "Configuration files were successfully migrated. Naev will now restart." );
            execv(argv[0], argv);
         }
         else { /* I sincerely hope this else is never hit. */
            dialogue_alert( "The update script encountered an error. Please exit Naev and move your config and save files manually:\n\n"
                  "\er%s/%s\e0 =>\n   \eD%s\e0\n\n"
                  "\er%s/%s\e0 =>\n   \eD%s\e0\n\n"
                  "\er%s/%s\e0 =>\n   \eD%snebula/\e0\n\n",
                  home, ".naev/conf.lua", nfile_configPath(),
                  home, ".naev/{saves,screenshots}/", nfile_dataPath(),
                  home, ".naev/gen/*.png", nfile_cachePath() );
         }
      }
      else {
Beispiel #3
0
void rnn_init() {
	LIBXML_TEST_VERSION
	xmlInitParser();
}
int main(int argc, char **argv)
{
	RsslError error;
	RsslUInt32 intervalSeconds = 0, currentRuntimeSec = 0;

	/* Read in configuration and echo it. */
	initNIProvPerfConfig(argc, argv);
	printNIProvPerfConfig(stdout);

	if (!(summaryFile = fopen(niProvPerfConfig.summaryFilename, "w")))
	{
		printf("Error: Failed to open file '%s'.\n", niProvPerfConfig.summaryFilename);
		exit(-1);
	}

	printNIProvPerfConfig(summaryFile); fflush(summaryFile);

	providerInit(&provider, PROVIDER_NONINTERACTIVE,
			processActiveChannel,
			processInactiveChannel,
			processMsg);

	// set up a signal handler so we can cleanup before exit
	signal(SIGINT, signal_handler);

	/* Determine update rates on per-tick basis */
	nsecPerTick = 1000000000LL/(RsslInt64)providerThreadConfig.ticksPerSec;

	xmlInitParser();

	/* Initialize RSSL */
	if (rsslInitialize(providerThreadConfig.threadCount > 1 ? RSSL_LOCK_GLOBAL : RSSL_LOCK_NONE, &error) != RSSL_RET_SUCCESS)
	{
		printf("rsslInitialize() failed.\n");
		exit(-1);
	}

	/* Initialize runtime timer */
	rsslProviderRuntime = getTimeNano() + ((RsslInt64)niProvPerfConfig.runTime * 1000000000LL);

	startProviderThreads(&provider, runNIProvConnection);

	/* this is the main loop */
	while(!signal_shutdown)
	{
		SLEEP(1);
		++currentRuntimeSec;
		++intervalSeconds;

		if (intervalSeconds == niProvPerfConfig.writeStatsInterval)
		{
			providerCollectStats(&provider, RSSL_TRUE, niProvPerfConfig.displayStats, 
					currentRuntimeSec, niProvPerfConfig.writeStatsInterval);
			intervalSeconds = 0;
		}
		
		/* Handle runtime. */
		if (getTimeNano() >= rsslProviderRuntime)
		{
			printf("\nRun time of %u seconds has expired.\n\n", niProvPerfConfig.runTime);
			signal_shutdown = RSSL_TRUE; /* Tell other threads to shutdown. */
		}


	}

	cleanUpAndExit();
}
Beispiel #5
0
/** Population a PCSCHEMA struct from the XML representation */
int
pc_schema_from_xml(const char *xml_str, PCSCHEMA **schema)
{
	xmlDocPtr xml_doc = NULL;
	xmlNodePtr xml_root = NULL;
	xmlNsPtr xml_ns = NULL;
	xmlXPathContextPtr xpath_ctx;
	xmlXPathObjectPtr xpath_obj;
	xmlNodeSetPtr nodes;
	PCSCHEMA *s;
	const char *xml_ptr = xml_str;

	/* Roll forward to start of XML string */
	while( (*xml_ptr != '\0') && (*xml_ptr != '<') )
	{
		xml_ptr++;
	}

	size_t xml_size = strlen(xml_ptr);
	static xmlChar *xpath_str = "/pc:PointCloudSchema/pc:dimension";
	static xmlChar *xpath_metadata_str = "/pc:PointCloudSchema/pc:metadata/Metadata";


	/* Parse XML doc */
	*schema = NULL;
	xmlInitParser();
	xml_doc = xmlReadMemory(xml_ptr, xml_size, NULL, NULL, 0);
	if ( ! xml_doc )
	{
		xmlCleanupParser();
		pcwarn("unable to parse schema XML");
		return PC_FAILURE;
	}

	/* Capture the namespace */
	xml_root = xmlDocGetRootElement(xml_doc);
	if ( xml_root->ns )
		xml_ns = xml_root->ns;

	/* Create xpath evaluation context */
	xpath_ctx = xmlXPathNewContext(xml_doc);
	if( ! xpath_ctx )
	{
		xmlFreeDoc(xml_doc);
		xmlCleanupParser();
		pcwarn("unable to create new XPath context to read schema XML");
		return PC_FAILURE;
	}

	/* Register the root namespace if there is one */
	if ( xml_ns )
		xmlXPathRegisterNs(xpath_ctx, "pc", xml_ns->href);

	/* Evaluate xpath expression */
	xpath_obj = xmlXPathEvalExpression(xpath_str, xpath_ctx);
	if( ! xpath_obj )
	{
	    xmlXPathFreeContext(xpath_ctx);
		xmlFreeDoc(xml_doc);
		xmlCleanupParser();
		pcwarn("unable to evaluate xpath expression \"%s\" against schema XML", xpath_str);
		return PC_FAILURE;
	}

	/* Iterate on the dimensions we found */
	if ( nodes = xpath_obj->nodesetval )
	{
		int ndims = nodes->nodeNr;
		int i;
		s = pc_schema_new(ndims);
		*schema = s;

		for ( i = 0; i < ndims; i++ )
		{
			/* This is a "dimension" */
			if( nodes->nodeTab[i]->type == XML_ELEMENT_NODE )
			{
				xmlNodePtr cur = nodes->nodeTab[i];
				xmlNodePtr child;
				PCDIMENSION *d = pc_dimension_new();
				char xydim = 0;

				/* These are the values of the dimension */
				for ( child = cur->children; child; child = child->next )
				{
					if( child->type == XML_ELEMENT_NODE )
					{
						if ( strcmp(child->name, "name") == 0 )
						{
							if ( strcasecmp(child->children->content, "X") == 0 ||
							     strcasecmp(child->children->content, "Longitude") == 0 ||
							     strcasecmp(child->children->content, "Lon") == 0 )
							{
								xydim = 'x';
							}
							if ( strcasecmp(child->children->content, "Y") == 0 ||
							     strcasecmp(child->children->content, "Latitude") == 0 ||
							     strcasecmp(child->children->content, "Lat") == 0 )
							{
								xydim = 'y';
							}
							d->name = pcstrdup(child->children->content);
						}
						else if ( strcmp(child->name, "description") == 0 )
							d->description = pcstrdup(child->children->content);
						else if ( strcmp(child->name, "size") == 0 )
							d->size = atoi(child->children->content);
						else if ( strcmp(child->name, "active") == 0 )
							d->active = atoi(child->children->content);
						else if ( strcmp(child->name, "position") == 0 )
							d->position = atoi(child->children->content) - 1;
						else if ( strcmp(child->name, "interpretation") == 0 )
							d->interpretation = pc_interpretation_number(child->children->content);
						else if ( strcmp(child->name, "scale") == 0 )
							d->scale = atof(child->children->content);
						else if ( strcmp(child->name, "offset") == 0 )
							d->offset = atof(child->children->content);
						else if ( strcmp(child->name, "uuid") == 0 )
							/* Ignore this tag for now */ 1;
						else if ( strcmp(child->name, "parent_uuid") == 0 )
							/* Ignore this tag for now */ 1;
						else
							pcinfo("unhandled schema type element \"%s\" encountered", child->name);
					}
				}

				/* Convert interprestation to size */
				d->size = pc_interpretation_size(d->interpretation);

				/* Store the dimension in the schema */
				if ( d->position >= 0 && d->position < ndims )
				{
					if ( s->dims[d->position] )
					{
						xmlXPathFreeObject(xpath_obj);
					    xmlXPathFreeContext(xpath_ctx);
						xmlFreeDoc(xml_doc);
						xmlCleanupParser();
						pc_schema_free(s);
						pcwarn("schema dimension at position \"%d\" is declared twice", d->position + 1, ndims);
						return PC_FAILURE;
					}
					if ( xydim == 'x' ) { s->x_position = d->position; }
					if ( xydim == 'y' ) { s->y_position = d->position; }
                    pc_schema_set_dimension(s, d);
				}
				else
				{
					xmlXPathFreeObject(xpath_obj);
				    xmlXPathFreeContext(xpath_ctx);
					xmlFreeDoc(xml_doc);
					xmlCleanupParser();
					pc_schema_free(s);
					pcwarn("schema dimension states position \"%d\", but number of XML dimensions is \"%d\"", d->position + 1, ndims);
					return PC_FAILURE;
				}
			}
		}

		/* Complete the byte offsets of dimensions from the ordered sizes */
		pc_schema_calculate_byteoffsets(s);
		/* Check X/Y positions */
		pc_schema_check_xy(s);
	}

	xmlXPathFreeObject(xpath_obj);

	/* SEARCH FOR METADATA ENTRIES */
	xpath_obj = xmlXPathEvalExpression(xpath_metadata_str, xpath_ctx);
	if( ! xpath_obj )
	{
	    xmlXPathFreeContext(xpath_ctx);
		xmlFreeDoc(xml_doc);
		xmlCleanupParser();
		pcwarn("unable to evaluate xpath expression \"%s\" against schema XML", xpath_metadata_str);
		return PC_FAILURE;
	}

	/* Iterate on the <Metadata> we find */
	if ( nodes = xpath_obj->nodesetval )
	{
		int i;

		for ( i = 0; i < nodes->nodeNr; i++ )
		{
            char *metadata_name = "";
            char *metadata_value = "";
		    /* Read the metadata name and value from the node */
		    /* <Metadata name="somename">somevalue</Metadata> */
		    xmlNodePtr cur = nodes->nodeTab[i];
            if( cur->type == XML_ELEMENT_NODE && strcmp(cur->name, "Metadata") == 0 )
            {
                metadata_name = xmlGetProp(cur, "name");
                metadata_value = xml_node_get_content(cur);
            }

            /* Store the compression type on the schema */
            if ( strcmp(metadata_name, "compression") == 0 )
            {
                int compression = pc_compression_number(metadata_value);
                if ( compression >= 0 )
                {
                    s->compression = compression;
                }
            }
            xmlFree(metadata_name);
        }
	}

	xmlXPathFreeObject(xpath_obj);

    xmlXPathFreeContext(xpath_ctx);
	xmlFreeDoc(xml_doc);
	xmlCleanupParser();

	return PC_SUCCESS;
}
Beispiel #6
0
int
main(int argc, char* argv[])
{
    ods_status status;
    engineconfig_type* cfg;
    int c;
    int options_index = 0;
    const char* cfgfile = ODS_SE_CFGFILE;
    static struct option long_options[] = {
        {"config", required_argument, 0, 'c'},
        {"help", no_argument, 0, 'h'},
        {"verbose", no_argument, 0, 'v'},
        { 0, 0, 0, 0}
    };

    argv0 = argv[0];

    /* parse the commandline */
    while ((c=getopt_long(argc, argv, "c:hv", long_options, &options_index)) != -1) {
        switch (c) {
            case 'c':
                cfgfile = optarg;
                break;
            case 'h':
                usage();
                exit(0);
            case 'v':
                ++verbosity;
                break;
            default:
                usage();
                exit(1);
        }
    }
    argc -= optind;
    argv += optind;
    if (argc != 0) {
        usage();
        exit(1);
    }

    ods_log_init("ods-migrate", 0, NULL, verbosity);

    xmlInitGlobals();
    xmlInitParser();
    xmlInitThreads();

    tzset(); /* for portability */

    /* Parse config file */
    cfg = engine_config(cfgfile, verbosity, NULL);
    cfg->verbosity = verbosity;
    /* does it make sense? */
    if (engine_config_check(cfg) != ODS_STATUS_OK) {
        abort(); /* TODO give some error, abort */
    }

    status = hsm_open2(parse_conf_repositories(cfgfile), hsm_prompt_pin);
    if (status != HSM_OK) {
        char* errorstr =  hsm_get_error(NULL);
        if (errorstr != NULL) {
            fprintf(stderr, "%s", errorstr);
            free(errorstr);
            abort(); /* FIXME */
        } else {
            fprintf(stderr,"error opening libhsm (errno %i)\n", status);
        }
        return 1;
    }
    dblayer_initialize();

    switch (cfg->db_type) {
        case ENFORCER_DATABASE_TYPE_SQLITE:
#ifdef HAVE_SQLITE3
            dblayer_sqlite3_open(cfg->datastore);
#else
            fprintf(stderr, "Database SQLite3 not available during compile-time.\n");
#endif
            break;
        case ENFORCER_DATABASE_TYPE_MYSQL:
#ifdef HAVE_MYSQL
            dblayer_mysql_open(cfg->db_host, cfg->db_username, cfg->db_password, cfg->datastore, cfg->db_port, NULL);
#else
    fprintf(stderr, "Database MySQL not available during compile-time.\n");
#endif
            break;
        case ENFORCER_DATABASE_TYPE_NONE:
        default:
            fprintf(stderr, "No database defined\n");
    }

    dblayer_foreach(listQueryStr, updateQueryStr, &compute);
    
    hsm_close();

    engine_config_cleanup(cfg);
    /* dblayer_foreach for each frees something dblayer_close uses
     * We better just let it leak. */
    /* dblayer_close(); */
    dblayer_finalize();
    ods_log_close();

    xmlCleanupParser();
    xmlCleanupGlobals();

    return 0;
}
Beispiel #7
0
XmlParser& XmlParser::xmlFile(const std::string& filePath) {
    xmlInitParser();
    _reader = xmlReaderForFile(filePath.c_str(), NULL, 0);
    return *this;
}
Beispiel #8
0
int main(int argc, char *argv[])
{
  ows *o;
  char *query;

  o = ows_init();
  o->config_file = buffer_init();

  /* Config Files */
  if (getenv("TINYOWS_CONFIG_FILE"))
    buffer_add_str(o->config_file, getenv("TINYOWS_CONFIG_FILE"));
  else if (getenv("TINYOWS_MAPFILE")) {
    buffer_add_str(o->config_file, getenv("TINYOWS_MAPFILE"));
    o->mapfile = true;
  } else
    buffer_add_str(o->config_file, OWS_CONFIG_FILE_PATH);

  LIBXML_TEST_VERSION
  xmlInitParser();

  /* Parse the configuration file and initialize ows struct */
  if (!o->exit) ows_parse_config(o, o->config_file->buf);
  if (!o->exit) ows_log(o, 2, "== TINYOWS STARTUP ==");

  /* Connect the ows to the database */
  if (!o->exit) ows_pg(o, o->pg_dsn->buf);
  if (!o->exit) ows_log(o, 2, "== Connection PostGIS ==");

  /* Fill layers storage metadata */
  if (!o->exit) ows_layers_storage_fill(o);
  if (!o->exit) ows_log(o, 2, "== Filling Storage ==");

  o->init = false;

#if TINYOWS_FCGI
  if (!o->exit) ows_log(o, 2, "== FCGI START ==");
  while (FCGI_Accept() >= 0) {
#endif

    query=NULL;
    if (!o->exit) query = cgi_getback_query(o);  /* Retrieve safely query string */
    if (!o->exit) ows_log(o, 4, query);          /* Log input query if asked */

    if (!o->exit && (!query || !strlen(query))) {
      /* Usage or Version command line options */
      if (argc > 1) {
        if (    !strncmp(argv[1], "--help", 6)
                || !strncmp(argv[1], "-h", 2)
                || !strncmp(argv[1], "--check", 7)) ows_usage(o);

        else if (    !strncmp(argv[1], "--version", 9)
                     || !strncmp(argv[1], "-v", 2))
          fprintf(stdout, "%s\n", TINYOWS_VERSION);

        else ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE, "Service Unknown", "service");

      } else ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE, "Service Unknown", "service");

      o->exit=true;  /* Have done what we have to */
    }

    if (!o->exit) o->request = ows_request_init();
    if (!o->exit) ows_kvp_or_xml(o, query);  /* Method is KVP or XML ? */

    if (!o->exit) {

      switch (o->request->method) {
        case OWS_METHOD_KVP:
          o->cgi = cgi_parse_kvp(o, query);
          break;
        case OWS_METHOD_XML:
          o->cgi = cgi_parse_xml(o, query);
          break;

        default:
          ows_error(o, OWS_ERROR_REQUEST_HTTP, "Wrong HTTP request Method", "http");
      }
    }

    if (!o->exit) o->psql_requests = list_init();
    if (!o->exit) ows_metadata_fill(o, o->cgi);                    /* Fill service's metadata */
    if (!o->exit) ows_request_check(o, o->request, o->cgi, query); /* Process service request */

    /* Run the right OWS service */
    if (!o->exit) {
      switch (o->request->service) {
        case WFS:
          o->request->request.wfs = wfs_request_init();
          wfs_request_check(o, o->request->request.wfs, o->cgi);
          if (!o->exit) wfs(o, o->request->request.wfs);
          break;
        default:
          ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE, "Service Unknown", "service");
      }
    }

    if (o->request) {
      ows_request_free(o->request);
      o->request=NULL;
    }

    /* We allocated memory only on post case */
    if (cgi_method_post() && query) free(query);

#if TINYOWS_FCGI
    fflush(stdout);
    o->exit = false;
  }
  ows_log(o, 2, "== FCGI SHUTDOWN ==");
  OS_LibShutdown();
#endif
  ows_log(o, 2, "== TINYOWS SHUTDOWN ==");
  ows_free(o);

  xmlCleanupParser();

  return EXIT_SUCCESS;
}
Beispiel #9
0
int main (int argc,char** argv)
{
    namespace po = boost::program_options;

    bool verbose = false;
    bool auto_open = false;
    int return_value = 0;
    std::vector<std::string> svg_files;
    mapnik::logger::instance().set_severity(mapnik::logger::error);

    try
    {
        po::options_description desc("svg2png utility");
        desc.add_options()
            ("help,h", "produce usage message")
            ("version,V","print version string")
            ("verbose,v","verbose output")
            ("open","automatically open the file after rendering (os x only)")
            ("svg",po::value<std::vector<std::string> >(),"svg file to read")
            ;

        po::positional_options_description p;
        p.add("svg",-1);
        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
        po::notify(vm);

        if (vm.count("version"))
        {
            std::clog <<"version " << MAPNIK_VERSION_STRING << std::endl;
            return 1;
        }

        if (vm.count("help"))
        {
            std::clog << desc << std::endl;
            return 1;
        }

        if (vm.count("verbose"))
        {
            verbose = true;
        }

        if (vm.count("open"))
        {
            auto_open = true;
        }

        if (vm.count("svg"))
        {
            svg_files=vm["svg"].as< std::vector<std::string> >();
        }
        else
        {
            std::clog << "please provide an svg file!" << std::endl;
            return -1;
        }

        std::vector<std::string>::const_iterator itr = svg_files.begin();
        if (itr == svg_files.end())
        {
            std::clog << "no svg files to render" << std::endl;
            return 0;
        }

        xmlInitParser();

        while (itr != svg_files.end())
        {
            std::string svg_name (*itr++);
            if (verbose)
            {
                std::clog << "found: " << svg_name << "\n";
            }

            std::shared_ptr<mapnik::marker const> marker = mapnik::marker_cache::instance().find(svg_name, false);
            main_marker_visitor visitor(svg_name, return_value, verbose, auto_open);
            mapnik::util::apply_visitor(visitor, *marker);
        }
    }
    catch (...)
    {
        std::clog << "Exception of unknown type!" << std::endl;
        xmlCleanupParser();
        return -1;
    }

    // only call this once, on exit
    // to make sure valgrind output is clean
    // http://xmlsoft.org/xmlmem.html
    xmlCleanupParser();
    return return_value;
}
BusConfigParser*
bus_config_load (const DBusString      *file,
                 dbus_bool_t            is_toplevel,
                 const BusConfigParser *parent,
                 DBusError             *error)

{
  xmlTextReader *reader;
  BusConfigParser *parser;
  DBusString dirname, data;
  DBusError tmp_error;
  int ret;
  
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
  parser = NULL;
  reader = NULL;

  if (!_dbus_string_init (&dirname))
    {
      _DBUS_SET_OOM (error);
      return NULL;
    }

  if (!_dbus_string_init (&data))
    {
      _DBUS_SET_OOM (error);
      _dbus_string_free (&dirname);
      return NULL;
    }

  if (is_toplevel)
    {
      /* xmlMemSetup only fails if one of the functions is NULL */
    /*
      xmlMemSetup (dbus_free,
                   dbus_malloc,
                   dbus_realloc,
                   _dbus_strdup);
     */              
      xmlInitParser ();
      xmlSetGenericErrorFunc (NULL, xml_shut_up);
    }

  if (!_dbus_string_get_dirname (file, &dirname))
    {
      _DBUS_SET_OOM (error);
      goto failed;
    }
  
  parser = bus_config_parser_new (&dirname, is_toplevel, parent);
  if (parser == NULL)
    {
      _DBUS_SET_OOM (error);
      goto failed;
    }
  
  if (!_dbus_file_get_contents (&data, file, error))
    goto failed;

  reader = xmlReaderForMemory (_dbus_string_get_const_data (&data), 
                               _dbus_string_get_length (&data),
			       NULL, NULL, 0);
  if (reader == NULL)
    {
      _DBUS_SET_OOM (error);
      goto failed;
    }

  xmlTextReaderSetParserProp (reader, XML_PARSER_SUBST_ENTITIES, 1);

  dbus_error_init (&tmp_error);
  xmlTextReaderSetStructuredErrorHandler (reader, xml_text_reader_error, &tmp_error);

  while ((ret = xmlTextReaderRead (reader)) == 1)
    {
      int type;
      
      if (dbus_error_is_set (&tmp_error))
        goto reader_out;

      type = xmlTextReaderNodeType (reader);
      if (type == -1)
        {
          _DBUS_MAYBE_SET_OOM (&tmp_error);
          goto reader_out;
        }

      switch ((xmlReaderTypes) type) {
      case XML_READER_TYPE_ELEMENT:
	xml_text_start_element (parser, reader, &tmp_error);
	break;

      case XML_READER_TYPE_TEXT:
      case XML_READER_TYPE_CDATA:
	{
	  DBusString content;
	  const char *value;
#ifdef __SYMBIAN32__
	  value = (const char *) xmlTextReaderConstValue (reader);
#else
	  value = xmlTextReaderConstValue (reader);
#endif
	  if (value != NULL)
	    {
	      _dbus_string_init_const (&content, value);
	      bus_config_parser_content (parser, &content, &tmp_error);
	    }
          else
            _DBUS_MAYBE_SET_OOM (&tmp_error);
	  break;
	}

      case XML_READER_TYPE_DOCUMENT_TYPE:
	{
	  const char *name;
#ifdef __SYMBIAN32__
	  name = (const char *) xmlTextReaderConstName (reader);
#else
	  name = xmlTextReaderConstName (reader);
#endif
	  if (name != NULL)
	    bus_config_parser_check_doctype (parser, name, &tmp_error);
          else
            _DBUS_MAYBE_SET_OOM (&tmp_error);
	  break;
	}

      case XML_READER_TYPE_END_ELEMENT:
	{
	  const char *name;
#ifdef __SYMBIAN32__
	  name = (const char *) xmlTextReaderConstName (reader);
#else
	  name = xmlTextReaderConstName (reader);
#endif
	  if (name != NULL)
	    bus_config_parser_end_element (parser, name, &tmp_error);
          else
            _DBUS_MAYBE_SET_OOM (&tmp_error);
	  break;
	}

      case XML_READER_TYPE_DOCUMENT:
      case XML_READER_TYPE_DOCUMENT_FRAGMENT:
      case XML_READER_TYPE_PROCESSING_INSTRUCTION:
      case XML_READER_TYPE_COMMENT:
      case XML_READER_TYPE_ENTITY:
      case XML_READER_TYPE_NOTATION:
      case XML_READER_TYPE_WHITESPACE:
      case XML_READER_TYPE_SIGNIFICANT_WHITESPACE:
      case XML_READER_TYPE_END_ENTITY:
      case XML_READER_TYPE_XML_DECLARATION:
	/* nothing to do, just read on */
	break;

      case XML_READER_TYPE_NONE:
      case XML_READER_TYPE_ATTRIBUTE:
      case XML_READER_TYPE_ENTITY_REFERENCE:
	_dbus_assert_not_reached ("unexpected nodes in XML");
      }

      if (dbus_error_is_set (&tmp_error))
        goto reader_out;
    }

  if (ret == -1)
    _DBUS_MAYBE_SET_OOM (&tmp_error);

 reader_out:
  xmlFreeTextReader (reader);
  reader = NULL;
  if (dbus_error_is_set (&tmp_error))
    {
      dbus_move_error (&tmp_error, error);
      goto failed;
    }
  
  if (!bus_config_parser_finished (parser, error))
    goto failed;
  _dbus_string_free (&dirname);
  _dbus_string_free (&data);
  if (is_toplevel)
    xmlCleanupParser();
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  return parser;
  
 failed:
  _DBUS_ASSERT_ERROR_IS_SET (error);
  _dbus_string_free (&dirname);
  _dbus_string_free (&data);
  if (is_toplevel)
    xmlCleanupParser();
  if (parser)
    bus_config_parser_unref (parser);
  _dbus_assert (reader == NULL); /* must go to reader_out first */
  return NULL;
}
Beispiel #11
0
 XmlContext ()
 {
   xmlInitParser ();
   LIBXML_TEST_VERSION
 }
Beispiel #12
0
int 
main(int argc, char **argv) {
    static const char secret_data[] = "Big secret";
    
    assert(argv);

    if(argc != 3) {
	printf_a_ignorar3(stderr, "Error: wrong number of arguments.\n");
	printf_a_ignorar3(stderr, "Usage: %s <tmpl-file> <key-file>\n", argv[0]);
	return(1);
    }

    /* Init libxml and libxslt libraries */
    xmlInitParser();
    LIBXML_TEST_VERSION
    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
    xmlSubstituteEntitiesDefault(1);
#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1; 
#endif /* XMLSEC_NO_XSLT */
        	
    /* Init xmlsec library */
    if(xmlSecInit() < 0) {
	printf_a_ignorar3(stderr, "Error: xmlsec initialization failed.\n");
	return(-1);
    }

    /* Check loaded library version */
    if(xmlSecCheckVersion() != 1) {
	printf_a_ignorar3(stderr, "Error: loaded xmlsec library version is not compatible.\n");
	return(-1);
    }

    /* Load default crypto engine if we are supporting dynamic
     * loading for xmlsec-crypto libraries. Use the crypto library
     * name ("openssl", "nss", etc.) to load corresponding 
     * xmlsec-crypto library.
     */
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
    if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
	printf_a_ignorar3(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
			"that you have it installed and check shared libraries path\n"
			"(LD_LIBRARY_PATH) envornment variable.\n");
	return(-1);	
    }
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */

    /* Init crypto library */
    if(xmlSecCryptoAppInit(NULL) < 0) {
	printf_a_ignorar3(stderr, "Error: crypto initialization failed.\n");
	return(-1);
    }

    /* Init xmlsec-crypto library */
    if(xmlSecCryptoInit() < 0) {
	printf_a_ignorar3(stderr, "Error: xmlsec-crypto initialization failed.\n");
	return(-1);
    }

    if(encrypt_file(argv[1], argv[2], secret_data, strlen(secret_data)) < 0) {
	return(-1);
    }    
    
    /* Shutdown xmlsec-crypto library */
    xmlSecCryptoShutdown();
    
    /* Shutdown crypto library */
    xmlSecCryptoAppShutdown();
    
    /* Shutdown xmlsec library */
    xmlSecShutdown();

    /* Shutdown libxslt/libxml */
#ifndef XMLSEC_NO_XSLT
    xsltCleanupGlobals();            
#endif /* XMLSEC_NO_XSLT */
    xmlCleanupParser();
    
    return(0);
}
Beispiel #13
0
void xml_parser_initialize()
{
	xmlInitParser ();
	xmlSetGenericErrorFunc(NULL, myXmlErrorReporting);
}
Beispiel #14
0
static void init_xml_lib(void)
{
	/* Init libxml */
	xmlInitParser();
	LIBXML_TEST_VERSION
}
/**
 * htmlDocDumpMemoryFormat:
 * @cur:  the document
 * @mem:  OUT: the memory pointer
 * @size:  OUT: the memory length
 * @format:  should formatting spaces been added
 *
 * Dump an HTML document in memory and return the xmlChar * and it's size.
 * It's up to the caller to free the memory.
 */
void
htmlDocDumpMemoryFormat(xmlDocPtr cur, xmlChar**mem, int *size, int format) {
    xmlOutputBufferPtr buf;
    xmlCharEncodingHandlerPtr handler = NULL;
    const char *encoding;

    xmlInitParser();

    if ((mem == NULL) || (size == NULL))
        return;
    if (cur == NULL) {
	*mem = NULL;
	*size = 0;
	return;
    }

    encoding = (const char *) htmlGetMetaEncoding(cur);

    if (encoding != NULL) {
	xmlCharEncoding enc;

	enc = xmlParseCharEncoding(encoding);
	if (enc != cur->charset) {
	    if (cur->charset != XML_CHAR_ENCODING_UTF8) {
		/*
		 * Not supported yet
		 */
		*mem = NULL;
		*size = 0;
		return;
	    }

	    handler = xmlFindCharEncodingHandler(encoding);
	    if (handler == NULL)
                htmlSaveErr(XML_SAVE_UNKNOWN_ENCODING, NULL, encoding);

	} else {
	    handler = xmlFindCharEncodingHandler(encoding);
	}
    }

    /*
     * Fallback to HTML or ASCII when the encoding is unspecified
     */
    if (handler == NULL)
	handler = xmlFindCharEncodingHandler("HTML");
    if (handler == NULL)
	handler = xmlFindCharEncodingHandler("ascii");

    buf = xmlAllocOutputBufferInternal(handler);
    if (buf == NULL) {
	*mem = NULL;
	*size = 0;
	return;
    }

    htmlDocContentDumpFormatOutput(buf, cur, NULL, format);

    xmlOutputBufferFlush(buf);
    if (buf->conv != NULL) {
	*size = buf->conv->use;
	*mem = xmlStrndup(buf->conv->content, *size);
    } else {
	*size = buf->buffer->use;
	*mem = xmlStrndup(buf->buffer->content, *size);
    }
    (void)xmlOutputBufferClose(buf);
}
Beispiel #16
0
/*
 *
 * Function: loadConfig
 * Description: 加载系统配置文件cmdsvr.xml
 * Input: 
 *      pczXmlConfig - 配置文件
 * OutPut:
 *      
 * Return:
 * Other:
 *
 */
int CommandServer::loadConfig( char *pczXmlConfig )
{
   xmlDocPtr  doc;
   xmlNodePtr node;

   LIBXML_TEST_VERSION
   xmlKeepBlanksDefault(0);

   xmlInitParser();

   m_pstConfig = (SystemConfig*)apr_palloc( m_pstRoot, sizeof(SystemConfig) );

   doc = xmlParseFile( pczXmlConfig );
   if( doc == NULL )
   {
      printf( "xmlParseFile( \"%s\" ) error!!\n ", pczXmlConfig );
      xmlCleanupParser();
      return -1;
   }

   /* 取根节点 */
   node = xmlDocGetRootElement( doc );
   if( node == NULL )
   {
      printf( "空的 xml 配置文件!!\n" );
      xmlFreeDoc( doc );
      xmlCleanupParser();
      return -1;
   }

   node = node->xmlChildrenNode;

   /**
     * 开始解析 xml 文件
     */
   while( node != NULL )
   {
      if( node->type == XML_ELEMENT_NODE )
      {
         xmlNodePtr txtNode = node->xmlChildrenNode;
         if( xmlStrcmp( node->name, (const xmlChar*)"port" ) == 0 )
         {
            m_pstConfig->m_iListenPort = atoi((char*)txtNode->content);
         }
         else if( xmlStrcmp( node->name, (const xmlChar*)"grpshmkey" ) == 0 )
         {
            m_pstConfig->m_iGrpShmKey = atoi((char*)txtNode->content);
         }
         else if( xmlStrcmp( node->name, (const xmlChar*)"prcshmkey" ) == 0 )
         {
            m_pstConfig->m_iPrcShmKey = atoi((char*)txtNode->content);
         }
         else if( xmlStrcmp( node->name, (const xmlChar*)"maxsys" ) == 0 )
         {
            m_pstConfig->m_iMaxSys = atoi((char*)txtNode->content);
         }
         else if( xmlStrcmp( node->name, (const xmlChar*)"maxchild" ) == 0 )
         {
            m_pstConfig->m_iMaxChild = atoi((char*)txtNode->content);
         }
      }
      node = node->next;
   } 

   xmlFreeDoc( doc );
   xmlCleanupParser();

   return 0;
}
int 
main(int argc, char **argv) {
    xmlSecKeysMngrPtr mngr;
#ifndef XMLSEC_NO_XSLT
    xsltSecurityPrefsPtr xsltSecPrefs = NULL;
#endif /* XMLSEC_NO_XSLT */
        
    /* start response */
    fprintf(stdout, "Content-type: text/plain\n");
    fprintf(stdout, "\n");
    
    /* Init libxml and libxslt libraries */
    xmlInitParser();
    LIBXML_TEST_VERSION
    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
    xmlSubstituteEntitiesDefault(1);
#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1; 
#endif /* XMLSEC_NO_XSLT */
    
    /* make sure that we print out everything to stdout */
    xmlGenericErrorContext = stdout;

    /* Init libxslt */
#ifndef XMLSEC_NO_XSLT
    /* disable everything */
    xsltSecPrefs = xsltNewSecurityPrefs(); 
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_READ_FILE,        xsltSecurityForbid);
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_WRITE_FILE,       xsltSecurityForbid);
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid);
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_READ_NETWORK,     xsltSecurityForbid);
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_WRITE_NETWORK,    xsltSecurityForbid);
    xsltSetDefaultSecurityPrefs(xsltSecPrefs); 
#endif /* XMLSEC_NO_XSLT */
                
    /* Init xmlsec library */
    if(xmlSecInit() < 0) {
        fprintf(stdout, "Error: xmlsec initialization failed.\n");
        return(-1);
    }

    /* Check loaded library version */
    if(xmlSecCheckVersion() != 1) {
        fprintf(stdout, "Error: loaded xmlsec library version is not compatible.\n");
        return(-1);
    }

    /* Load default crypto engine if we are supporting dynamic
     * loading for xmlsec-crypto libraries. Use the crypto library
     * name ("openssl", "nss", etc.) to load corresponding 
     * xmlsec-crypto library.
     */
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
    if(xmlSecCryptoDLLoadLibrary(NULL) < 0) {
        fprintf(stdout, "Error: unable to load default xmlsec-crypto library. Make sure\n"
                        "that you have it installed and check shared libraries path\n"
                        "(LD_LIBRARY_PATH) envornment variable.\n");
        return(-1);     
    }
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */

    /* Init crypto library */
    if(xmlSecCryptoAppInit(XMLDSIGVERIFY_DEFAULT_TRUSTED_CERTS_FOLDER) < 0) {
        fprintf(stdout, "Error: crypto initialization failed.\n");
        return(-1);
    }

    /* Init xmlsec-crypto library */
    if(xmlSecCryptoInit() < 0) {
        fprintf(stdout, "Error: xmlsec-crypto initialization failed.\n");
        return(-1);
    }

    /* create keys manager */
    mngr = xmlSecKeysMngrCreate();
    if(mngr == NULL) {
        fprintf(stdout, "Error: failed to create keys manager.\n");
        return(-1);
    }
    if(xmlSecCryptoAppDefaultKeysMngrInit(mngr) < 0) {
        fprintf(stdout, "Error: failed to initialize keys manager.\n");
        return(-1);
    }    

    if(load_keys(mngr, XMLDSIGVERIFY_KEY_AND_CERTS_FOLDER, 0) < 0) {
        xmlSecKeysMngrDestroy(mngr);
        return(-1);
    }
    
    if(load_trusted_certs(mngr, XMLDSIGVERIFY_KEY_AND_CERTS_FOLDER, 0) < 0) {
        xmlSecKeysMngrDestroy(mngr);
        return(-1);
    }

    if(verify_request(mngr) < 0) {
        xmlSecKeysMngrDestroy(mngr);
        return(-1);
    }    

    /* Destroy keys manager */
    xmlSecKeysMngrDestroy(mngr);
        
    /* Shutdown xmlsec-crypto library */
    xmlSecCryptoShutdown();
    
    /* Shutdown crypto library */
    xmlSecCryptoAppShutdown();
    
    /* Shutdown xmlsec library */
    xmlSecShutdown();

    /* Shutdown libxslt/libxml */
#ifndef XMLSEC_NO_XSLT
    xsltFreeSecurityPrefs(xsltSecPrefs);
    xsltCleanupGlobals();            
#endif /* XMLSEC_NO_XSLT */

    xmlCleanupParser();
    
    return(0);
}
Beispiel #18
0
/**
 * rtevald_parser main function.
 *
 * @param argc
 * @param argv
 *
 * @return Returns the result of the process_submission_queue() function.
 */
int main(int argc, char **argv) {
        eurephiaVALUES *config = NULL, *prgargs = NULL;
        char xsltfile[2050], *reportdir = NULL;
	xsltStylesheet *xslt = NULL;
	dbconn *dbc = NULL;
        pthread_t **threads = NULL;
        pthread_attr_t **thread_attrs = NULL;
	pthread_mutex_t mtx_sysreg = PTHREAD_MUTEX_INITIALIZER;
	pthread_mutex_t mtx_thrcnt = PTHREAD_MUTEX_INITIALIZER;
	threadData_t **thrdata = NULL;
	struct mq_attr msgq_attr;
	mqd_t msgq = 0;
	int i,rc, mq_init = 0, max_threads = 0, started_threads = 0, activethreads = 0;
	unsigned int max_report_size = 0;

	// Initialise XML and XSLT libraries
	xsltInit();
	xmlInitParser();

	prgargs = parse_arguments(argc, argv);
	if( prgargs == NULL ) {
		fprintf(stderr, "** ERROR **  Failed to parse program arguments\n");
		rc = 2;
		goto exit;
	}

	// Setup a log context
	logctx = init_log(eGet_value(prgargs, "log"), eGet_value(prgargs, "loglevel"));
	if( !logctx ) {
		fprintf(stderr, "** ERROR **  Could not setup a log context\n");
		eFree_values(prgargs);
		rc = 2;
		goto exit;
	}

	// Fetch configuration
        config = read_config(logctx, prgargs, "xmlrpc_parser");
	eFree_values(prgargs); // read_config() copies prgargs into config, we don't need prgargs anymore

	// Daemonise process if requested
	if( atoi_nullsafe(eGet_value(config, "daemon")) == 1 ) {
		if( daemonise(logctx) < 1 ) {
			rc = 3;
			goto exit;
		}
	}


	// Parse XSLT template
	snprintf(xsltfile, 512, "%s/%s", eGet_value(config, "xsltpath"), XMLPARSER_XSL);
	writelog(logctx, LOG_DEBUG, "Parsing XSLT file: %s", xsltfile);
        xslt = xsltParseStylesheetFile((xmlChar *) xsltfile);
	if( !xslt ) {
		writelog(logctx, LOG_EMERG, "Could not parse XSLT template: %s", xsltfile);
		rc = 2;
		goto exit;
	}

	// Open a POSIX MQ
	writelog(logctx, LOG_DEBUG, "Preparing POSIX MQ queue: /rteval_parsequeue");
	memset(&msgq, 0, sizeof(mqd_t));
	msgq_attr.mq_maxmsg = get_mqueue_msg_max(logctx);
	msgq_attr.mq_msgsize = sizeof(parseJob_t);
	msgq_attr.mq_flags = O_NONBLOCK;
	msgq = mq_open("/rteval_parsequeue", O_RDWR | O_CREAT, 0600, &msgq_attr);
	if( msgq < 0 ) {
		writelog(logctx, LOG_EMERG,
			 "Could not open message queue: %s", strerror(errno));
		rc = 2;
		goto exit;
	}
	mq_init = 1;

	// Get the number of worker threads
	max_threads = atoi_nullsafe(eGet_value(config, "threads"));
	if( max_threads == 0 ) {
		max_threads = 4;
	}

	// Get a database connection for the main thread
        dbc = db_connect(config, max_threads, logctx);
        if( !dbc ) {
		rc = 4;
		goto exit;
        }

	// Prepare all threads
	threads = calloc(max_threads + 1, sizeof(pthread_t *));
	thread_attrs = calloc(max_threads + 1, sizeof(pthread_attr_t *));
	thrdata = calloc(max_threads + 1, sizeof(threadData_t *));
	assert( (threads != NULL) && (thread_attrs != NULL) && (thrdata != NULL) );

	reportdir = eGet_value(config, "reportdir");
	writelog(logctx, LOG_INFO, "Starting %i worker threads", max_threads);
	max_report_size = defaultIntValue(atoi_nullsafe(eGet_value(config, "max_report_size")), 1024*1024);
	for( i = 0; i < max_threads; i++ ) {
		// Prepare thread specific data
		thrdata[i] = malloc_nullsafe(logctx, sizeof(threadData_t));
		if( !thrdata[i] ) {
			writelog(logctx, LOG_EMERG,
				 "Could not allocate memory for thread data");
			rc = 2;
			goto exit;
		}

		// Get a database connection for the thread
		thrdata[i]->dbc = db_connect(config, i, logctx);
		if( !thrdata[i]->dbc ) {
			writelog(logctx, LOG_EMERG,
				"Could not connect to the database for thread %i", i);
			rc = 2;
			shutdown = 1;
			goto exit;
		}

		thrdata[i]->shutdown = &shutdown;
		thrdata[i]->threadcount = &activethreads;
		thrdata[i]->mtx_thrcnt = &mtx_thrcnt;
		thrdata[i]->id = i;
		thrdata[i]->msgq = msgq;
		thrdata[i]->mtx_sysreg = &mtx_sysreg;
		thrdata[i]->xslt = xslt;
		thrdata[i]->destdir = reportdir;
		thrdata[i]->max_report_size = max_report_size;

		thread_attrs[i] = malloc_nullsafe(logctx, sizeof(pthread_attr_t));
		if( !thread_attrs[i] ) {
			writelog(logctx, LOG_EMERG,
				"Could not allocate memory for thread attributes");
			rc = 2;
			goto exit;
		}
		pthread_attr_init(thread_attrs[i]);
		pthread_attr_setdetachstate(thread_attrs[i], PTHREAD_CREATE_JOINABLE);

		threads[i] = malloc_nullsafe(logctx, sizeof(pthread_t));
		if( !threads[i] ) {
			writelog(logctx, LOG_EMERG,
				"Could not allocate memory for pthread_t");
			rc = 2;
			goto exit;
		}
	}

	// Setup signal catching
	signal(SIGINT,  sigcatch);
	signal(SIGTERM, sigcatch);
	signal(SIGHUP,  SIG_IGN);
	signal(SIGUSR1, sigcatch);
	signal(SIGUSR2, SIG_IGN);

	// Start the threads
	for( i = 0; i < max_threads; i++ ) {
		int thr_rc = pthread_create(threads[i], thread_attrs[i], parsethread, thrdata[i]);
		if( thr_rc < 0 ) {
			writelog(logctx, LOG_EMERG,
				 "** ERROR **  Failed to start thread %i: %s",
				 i, strerror(thr_rc));
			rc = 3;
			goto exit;
		}
		started_threads++;
	}

	// Main routine
	//
	// checks the submission queue and puts unprocessed records on the POSIX MQ
	// to be parsed by one of the threads
	//
	sleep(3); // Allow at least a few parser threads to settle down first before really starting
	writelog(logctx, LOG_DEBUG, "Starting submission queue checker");
	rc = process_submission_queue(dbc, msgq, &activethreads);
	writelog(logctx, LOG_DEBUG, "Submission queue checker shut down");

 exit:
	// Clean up all threads
	for( i = 0; i < max_threads; i++ ) {
		// Wait for all threads to exit
		if( (i < started_threads) && threads && threads[i] ) {
			void *thread_rc;
			int j_rc;

			if( (j_rc = pthread_join(*threads[i], &thread_rc)) != 0 ) {
				writelog(logctx, LOG_CRIT,
					 "Failed to join thread %i: %s",
					 i, strerror(j_rc));
			}
			pthread_attr_destroy(thread_attrs[i]);
		}
		if( threads ) {
			free_nullsafe(threads[i]);
		}
		if( thread_attrs ) {
			free_nullsafe(thread_attrs[i]);
		}

		// Disconnect threads database connection
		if( thrdata && thrdata[i] ) {
			db_disconnect(thrdata[i]->dbc);
			free_nullsafe(thrdata[i]);
		}
	}
	free_nullsafe(thrdata);
	free_nullsafe(threads);
	free_nullsafe(thread_attrs);

	// Close message queue
	if( mq_init == 1 ) {
		errno = 0;
		if( mq_close(msgq) < 0 ) {
			writelog(logctx, LOG_CRIT, "Failed to close message queue: %s",
				 strerror(errno));
		}
		errno = 0;
		if( mq_unlink("/rteval_parsequeue") < 0 ) {
			writelog(logctx, LOG_ALERT, "Failed to remove the message queue: %s",
				 strerror(errno));
		}
	}

	// Disconnect from database, main thread connection
	db_disconnect(dbc);

	// Free up the rest
	eFree_values(config);
	xsltFreeStylesheet(xslt);
	xmlCleanupParser();
	xsltCleanupGlobals();

	writelog(logctx, LOG_EMERG, "rteval-parserd is stopped");
	close_log(logctx);
	return rc;
}
Beispiel #19
0
Datei: board.cpp Projekt: fkp/src
bool Board::InitFromXMLFile(const char * fileName)
{
  bool toReturn = false;
  xmlDocPtr doc;
  xmlXPathContextPtr xpathCtx; 
  xmlXPathObjectPtr xpathObj; 
  int ret;

  // Init libxml
  xmlInitParser();
  LIBXML_TEST_VERSION

  assert(fileName);
  assert(XPathExpression);

  // Load XML document
  doc = xmlParseFile(fileName);

  if (doc == NULL)
  {
    cout << "Error: unable to parse file " << fileName << endl;
    return false;
  }

  // Create xpath evaluation context
  xpathCtx = xmlXPathNewContext(doc);
  if(xpathCtx == NULL)
  {
    cout << "Error: unable to create new XPath context" << endl;
    xmlFreeDoc(doc); 
    return false;
  }
    
  // Evaluate xpath expression
  xpathObj = xmlXPathEvalExpression(BAD_CAST XPathExpression, xpathCtx);
  if(xpathObj == NULL)
  {
    cout << "Error: unable to evaluate xpath expression " << XPathExpression << endl;
    xmlXPathFreeContext(xpathCtx); 
    xmlFreeDoc(doc); 
    return false;
  }

  // Process the nodes in the file
  toReturn = ProcessNodes(xpathObj->nodesetval, stdout);

  // Cleanup
  xmlXPathFreeObject(xpathObj);
  xmlXPathFreeContext(xpathCtx); 
  xmlFreeDoc(doc); 
    
  // Shutdown libxml
  xmlCleanupParser();
    
  // This is to debug memory for regression tests
  xmlMemoryDump();

  // Build the UI table with the squares we have
  BuildTable();

  return toReturn;
}
Beispiel #20
0
int main(int argc, char *argv[])
{
    char *descr;
    Board board;
    xmlDocPtr doc;
    xmlNodePtr gameNode, boardNode, analysisNode, node;

    if (argc != 2)
    {
        printf("usage: analyze <game.xml>\n");
        exit(1);
    }

    LIBXML_TEST_VERSION

    /* Parse input file */
    xmlInitParser();
    doc = xmlReadFile(argv[1], NULL, 0);
    if (doc == NULL)
    {
        fprintf(stderr, "Could not read/parse input file.\n");
        exit(1);
    }
    xmlCleanupParser();

    /* Process input data */
    gameNode = xmlDocGetRootElement(doc);
    if (strcmp((char*)gameNode->name, "game") != 0)
    {
        fprintf(stderr, "Root element should be <game>\n");
        exit(1);
    }
    boardNode = NULL;
    for (node = gameNode->children; node != NULL; node = node->next)
    {
        if (node->type == XML_ELEMENT_NODE)
        {
            if (strcmp((char*)node->name, "board") == 0)
            {
                if (boardNode != NULL)
                {
                    fprintf(stderr, "Multiple Mboard> elements found.\n");
                    exit(1);
                }
                boardNode = node;
            }
            if (strcmp((char*)node->name, "analysis") == 0)
            {
                xmlUnlinkNode(node);
                xmlFreeNode(node);
            }
        }
    }
    if (boardNode == NULL)
    {
        fprintf(stderr, "No <board> element found.\n");
        exit(1);
    }
    if ( boardNode->children == NULL ||
         boardNode->children != boardNode->last ||
         boardNode->children->type != XML_TEXT_NODE )
    {
        fprintf(stderr, "<board> should contain only text.\n");
        exit(1);
    }
    descr = (char*)xmlNodeGetContent(boardNode->children);

    /* Decode board */
    if (!board_decode_full(&board, descr))
    {
        fprintf(stderr, "Cannot decode full board description: %s\n", descr);
        exit(1);
    }

    /* Add analysis to data */
    analysisNode = analyze_board(&board);
    xmlAddChild(gameNode, analysisNode);

    /* Write output document */
    xmlDocDump(stdout, doc);
    xmlFreeDoc(doc);

    return 0;
}
Beispiel #21
0
XmlParser& XmlParser::xmlString(const std::string& xmlString) {
    xmlInitParser();
    const char* cstr = xmlString.c_str();
    _reader = xmlReaderForMemory(cstr, (int)strlen(cstr), NULL, NULL, 0);
    return *this;
}
Beispiel #22
0
int 
main(int argc, char **argv) {
#ifndef XMLSEC_NO_XSLT
    xsltSecurityPrefsPtr xsltSecPrefs = NULL;
#endif /* XMLSEC_NO_XSLT */

    assert(argv);

    if(argc != 4) {
        fprintf(stderr, "Error: wrong number of arguments.\n");
        fprintf(stderr, "Usage: %s <xml-file> <key-file> <cert-file>\n", argv[0]);
        return(1);
    }

    /* Init libxml and libxslt libraries */
    xmlInitParser();
    LIBXML_TEST_VERSION
    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
    xmlSubstituteEntitiesDefault(1);
#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1; 
#endif /* XMLSEC_NO_XSLT */

    /* Init libxslt */
#ifndef XMLSEC_NO_XSLT
    /* disable everything */
    xsltSecPrefs = xsltNewSecurityPrefs(); 
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_READ_FILE,        xsltSecurityForbid);
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_WRITE_FILE,       xsltSecurityForbid);
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid);
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_READ_NETWORK,     xsltSecurityForbid);
    xsltSetSecurityPrefs(xsltSecPrefs,  XSLT_SECPREF_WRITE_NETWORK,    xsltSecurityForbid);
    xsltSetDefaultSecurityPrefs(xsltSecPrefs); 
#endif /* XMLSEC_NO_XSLT */
                
    /* Init xmlsec library */
    if(xmlSecInit() < 0) {
        fprintf(stderr, "Error: xmlsec initialization failed.\n");
        return(-1);
    }

    /* Check loaded library version */
    if(xmlSecCheckVersion() != 1) {
        fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
        return(-1);
    }

    /* Load default crypto engine if we are supporting dynamic
     * loading for xmlsec-crypto libraries. Use the crypto library
     * name ("openssl", "nss", etc.) to load corresponding 
     * xmlsec-crypto library.
     */
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
    if(xmlSecCryptoDLLoadLibrary(NULL) < 0) {
        fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
                        "that you have it installed and check shared libraries path\n"
                        "(LD_LIBRARY_PATH and/or LTDL_LIBRARY_PATH) envornment variables.\n");
        return(-1);     
    }
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */

    /* Init crypto library */
    if(xmlSecCryptoAppInit(NULL) < 0) {
        fprintf(stderr, "Error: crypto initialization failed.\n");
        return(-1);
    }

    /* Init xmlsec-crypto library */
    if(xmlSecCryptoInit() < 0) {
        fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
        return(-1);
    }

    if(sign_file(argv[1], argv[2], argv[3]) < 0) {
        return(-1);
    }    
    
    /* Shutdown xmlsec-crypto library */
    xmlSecCryptoShutdown();
    
    /* Shutdown crypto library */
    xmlSecCryptoAppShutdown();
    
    /* Shutdown xmlsec library */
    xmlSecShutdown();

    /* Shutdown libxslt/libxml */
#ifndef XMLSEC_NO_XSLT
    xsltFreeSecurityPrefs(xsltSecPrefs);
    xsltCleanupGlobals();            
#endif /* XMLSEC_NO_XSLT */
    xmlCleanupParser();
    
    return(0);
}
int main(int argc, char **argv)
{
    if (argc != 4)
    {
        usage();
    }

    url = argv[1];
    char *username = argv[2];
    char *password = argv[3];

    xmlInitParser();
    xen_init();
    curl_global_init(CURL_GLOBAL_ALL);

#define CLEANUP                                 \
    do {                                        \
        xen_session_logout(session);            \
        curl_global_cleanup();                  \
        xen_fini();                             \
        xmlCleanupParser();                     \
    } while(0)                                  \

    
    xen_session *session =
        xen_session_login_with_password(call_func, NULL, username, password);

    struct xen_string_set *classes = xen_string_set_alloc(0);
    xen_event_register(session, classes);
    xen_string_set_free(classes);

    if (!session->ok)
    {
        print_error(session);
        CLEANUP;
        return 1;
    }

    while (true)
    {
        struct xen_event_record_set *events;
        if (!xen_event_next(session, &events))
        {
            print_error(session);
            CLEANUP;
            return 1;
        }

        for (size_t i = 0; i < events->size; i++)
        {
            xen_event_record *ev = events->contents[i];
            char time[256];
            struct tm *tm = localtime(&ev->timestamp);
            my_strftime(time, 256, "%c, local time", tm);
            printf("Event received: ID = %"PRId64", %s.\n", ev->id, time);
            switch (ev->operation)
            {
            case XEN_EVENT_OPERATION_ADD:
                printf("%s created with UUID %s.\n", ev->class, ev->obj_uuid);
                break;

            case XEN_EVENT_OPERATION_DEL:
                printf("%s with UUID %s deleted.\n", ev->class, ev->obj_uuid);
                break;

            case XEN_EVENT_OPERATION_MOD:
                printf("%s with UUID %s modified.\n", ev->class, ev->obj_uuid);
                break;
            default:
                assert(false);
            }
        }

        xen_event_record_set_free(events);
    }

    CLEANUP;

    return 0;
}
Beispiel #24
0
XMLParser::XMLParser(void)
{
    xmlInitParser();
}
Beispiel #25
0
/* point-of-entry */
int 
main(int argc, char **argv)
{
	int ret = -1, c, index, action = ACTION_NONE, tmp;
	char *action_param = NULL;
        processor_config_t *config = 0, *config2 = 0;
	char *conf_file = 0;
	int load_autoreg = 0;
	int flag_quiet = 0;
	int log_to_file = 0;
	int console_only = 0;
	int do_test = 0; // do whatever the test of the day is

	xmlInitParser();
	xmlInitThreads();
	//initGenericErrorDefaultFunc((xmlGenericErrorFunc *)xml_error_func);

        /* the getopt values */
        static struct option long_options[] =
                {                        
                        {"verbose", no_argument, 0, 0},
                        {"iface", required_argument, 0, 0},
                        {"threads", required_argument, 0, 0},
                        {"help", no_argument, 0, 0},
                        {"version", no_argument, 0, 0},
                        {"console", no_argument, 0, 0},
#ifdef CONFIG_PYTHON_ENABLED
                        {"shell", no_argument, 0, 0},
                        {"run", required_argument, 0, 0},
                        {"no-scripts", no_argument, 0, 0},
#endif
#ifdef CONFIG_SIP_ENABLED
                        {"proxy-iface", required_argument, 0, 0},
                        {"no-mp", no_argument, 0, 0},
                        {"tunnel-mp", no_argument, 0, 0},
                        {"force-mp", no_argument, 0, 0},
                        {"allow-unknown", no_argument, 0, 0},
                        {"allow-untrusted", no_argument, 0, 0},
#endif
                        {"list-ca", no_argument, 0, 0},
                        {"import-ca", required_argument, 0, 0},
                        {"remove-ca", required_argument, 0, 0},
                        {"list", no_argument, 0, 0},
                        {"import", required_argument, 0, 0},
                        {"remove", required_argument, 0, 0},
                        {"idents", required_argument, 0, 0},
                        {"log", required_argument, 0, 0},
#ifdef CONFIG_BROADCAST_ENABLED
                        {"bc-addr", required_argument, 0, 0},
#endif
#ifdef CONFIG_WEBCONF_ENABLED
                        {"webconf", required_argument, 0, 0},
#endif
#ifdef CONFIG_OPENDHT_ENABLED
                        {"opendht", required_argument, 0, 0},
#endif
#ifdef CONFIG_HIP_ENABLED
                        {"list-hits", no_argument, 0, 0},
                        {"rvs", required_argument, 0, 0},
                        {"provide-rvs", no_argument, 0, 0},
#endif
                        {0, 0, 0, 0}
                };        

#ifdef LOCK_DEBUG
	debug2_init();
#endif
#ifdef REF_DEBUG2
	ship_debug_initref();
#endif


	if (!(config = processor_config_new()) || !(config2 = processor_config_new())) {
                USER_ERROR("Error loading application\n");
		goto err;
	}

	if (processor_config_load_defaults(config2)) {
                USER_ERROR("Error loading default configurations\n");
                goto err;
	}
	processor_config_get_string(config2, P2PSHIP_CONF_CONF_FILE, &conf_file);

        opterr = 0;
        while ((c = getopt_long(argc, argv, "LqvhDVs:c:p:i:Rr:kKt", long_options, &index)) != -1) {
                
                if (!c) {
                        if (!strcmp(long_options[index].name, "threads")) {
				processor_config_set_int(config, P2PSHIP_CONF_WORKER_THREADS, atoi(optarg));
                        } else if (!strcmp(long_options[index].name, "help")) {
                                c = '?';
                        } else if (!strcmp(long_options[index].name, "version")) {
                                c = 'V';
                        } else if (!strcmp(long_options[index].name, "verbose")) {
                                c = 'v';
                        } else if (!strcmp(long_options[index].name, "iface")) {
                                c = 'i';
                        } else if (!strcmp(long_options[index].name, "console")) {
				console_only = 1;
#ifdef CONFIG_PYTHON_ENABLED
                        } else if (!strcmp(long_options[index].name, "shell")) {
				processor_config_set_true(config, P2PSHIP_CONF_START_SHELL);
                        } else if (!strcmp(long_options[index].name, "run")) {
				processor_config_set_string(config, P2PSHIP_CONF_RUN_SCRIPT, optarg);
                        } else if (!strcmp(long_options[index].name, "no-scripts")) {
				processor_config_set_false(config, P2PSHIP_CONF_STARTUP_SCRIPTS);
#endif
#ifdef CONFIG_SIP_ENABLED
                        } else if (!strcmp(long_options[index].name, "proxy-iface")) {
				processor_config_set_string(config, P2PSHIP_CONF_SIPP_PROXY_IFACES, optarg);
                        } else if (!strcmp(long_options[index].name, "no-mp")) {
				processor_config_set_string(config, P2PSHIP_CONF_SIPP_MEDIA_PROXY, "no");
                        } else if (!strcmp(long_options[index].name, "tunnel-mp")) {
				processor_config_set_string(config, P2PSHIP_CONF_SIPP_TUNNEL_PROXY, "yes");
                        } else if (!strcmp(long_options[index].name, "force-mp")) {
				processor_config_set_string(config, P2PSHIP_CONF_SIPP_FORCE_PROXY, "yes");
                        } else if (!strcmp(long_options[index].name, "allow-unknown")) {
				processor_config_set_string(config, P2PSHIP_CONF_IDENT_ALLOW_UNKNOWN_REGISTRATIONS, "yes");
                        } else if (!strcmp(long_options[index].name, "allow-untrusted")) {
				processor_config_set_string(config, P2PSHIP_CONF_IDENT_ALLOW_UNTRUSTED, "yes");
#endif
                        } else if (!action && !strcmp(long_options[index].name, "list-ca")) {
				action = ACTION_LIST_CA;
                        } else if (!action && !strcmp(long_options[index].name, "remove-ca")) {
				action = ACTION_REMOVE_CA;
				if (!action_param) action_param = strdup(optarg);
                        } else if (!action && !strcmp(long_options[index].name, "import-ca")) {
				action = ACTION_IMPORT_CA;
				if (!action_param) action_param = strdup(optarg);
			} else if (!action && !strcmp(long_options[index].name, "list")) {
				action = ACTION_LIST;
                        } else if (!action && !strcmp(long_options[index].name, "remove")) {
				action = ACTION_REMOVE;
				if (!action_param) action_param = strdup(optarg);
                        } else if (!action && !strcmp(long_options[index].name, "import")) {
				action = ACTION_IMPORT;
				if (!action_param) action_param = strdup(optarg);
                        } else if (!strcmp(long_options[index].name, "idents")) {
				processor_config_set_string(config, P2PSHIP_CONF_IDENTS_FILE, optarg);
                        } else if (!strcmp(long_options[index].name, "log")) {
				processor_config_set_string(config, P2PSHIP_CONF_LOG_FILE, optarg);
#ifdef CONFIG_BROADCAST_ENABLED
                        } else if (!strcmp(long_options[index].name, "bc-addr")) {
				processor_config_set_string(config, P2PSHIP_CONF_BC_ADDR, optarg);
#endif
#ifdef CONFIG_OPENDHT_ENABLED
                        } else if (!strcmp(long_options[index].name, "opendht")) {
				processor_config_set_string(config, P2PSHIP_CONF_OPENDHT_PROXY, optarg);
#endif
#ifdef CONFIG_HIP_ENABLED
                        } else if (!strcmp(long_options[index].name, "list-hits")) {
				action = ACTION_LIST_HITS;
                        } else if (!strcmp(long_options[index].name, "rvs")) {
				processor_config_set_string(config, P2PSHIP_CONF_RVS, optarg);
                        } else if (!strcmp(long_options[index].name, "provide-rvs")) {
				processor_config_set_string(config, P2PSHIP_CONF_PROVIDE_RVS, "yes");
#endif
#ifdef CONFIG_WEBCONF_ENABLED
                        } else if (!strcmp(long_options[index].name, "webconf")) {
				processor_config_set_string(config, P2PSHIP_CONF_WEBCONF_SS, optarg);
#endif
			} else {
				c  = '?';
			}
		}

                switch (c) {    
                case 0:
                        /* already processed */
                        break;
                case 'v':
                        if (p2pship_log_level > -1)
                                p2pship_log_level++;
                        break;
                case 'q':
                        flag_quiet = 1;
                        p2pship_log_level = -1;
                        break;
                case 'D':
			log_to_file = 1;
			processor_config_set_string(config, P2PSHIP_CONF_DAEMON, "yes");
                        break;
                case 'c':
                        conf_file = optarg;
			processor_config_set_string(config, P2PSHIP_CONF_CONF_FILE, conf_file);
                        break;
                case 'i':
			processor_config_set_string(config, P2PSHIP_CONF_IFACES, optarg);
                        break;
#ifdef CONFIG_SIP_ENABLED
                case 'p':
                        if (sscanf(optarg, "%u", &tmp) != 1) {
                                USER_ERROR("Invalid port %s\n", optarg);
                                return 1;
                        } else {
				processor_config_set_int(config, P2PSHIP_CONF_SIPP_PROXY_PORT, tmp);
			}
                        break;
#endif
                case 's':
                        if (sscanf(optarg, "%u", &tmp) != 1) {
                                USER_ERROR("Invalid port %s\n", optarg);
                                return 1;
                        } else {
				processor_config_set_int(config, P2PSHIP_CONF_SHIP_PORT, tmp);
			}
                        break;
                case 'V':
                        print_version();
                        return 0;
		case 'R':
			load_autoreg = 1;
			break;
		case 'r':
			processor_config_set_string(config, P2PSHIP_CONF_AUTOREG_FILE, optarg);
			break;
		case 'L':
			log_to_file = 1;
			break;
                case 'k':
			processor_kill_existing_pid();
			break;
                case 'K':
			processor_kill_all_existing();
			break;
                case 't':
			do_test = 1;
			break;
                case 'h':
                case '?':
                default:
                        print_version();
                        print_usage();
                        return 1;
                }
        }
        
        if (!flag_quiet)
                print_version();
     
        /* 1. load the defaults (done already), 2. load the conf file, 3. put on the manual overrides */
	/* ensure that we have a config file! */
	if (ship_ensure_file(conf_file, "# Autocreated\n\n") || 
	    processor_config_load(config2, conf_file)) {
		USER_ERROR("Error processing config file %s\n", conf_file);
		goto err;
	}
        
        if (processor_config_transfer(config2, config)) {
                USER_ERROR("Error processing configs\n");
                goto err;
        }

	/* transfer */
	processor_config_free(config);
	config = config2;
	config2 = NULL;

	/* ok, ready to rock! */
	processor_config_ensure_configs(config);
	if (log_to_file) {
		p2pship_log_file = processor_config_string(config, P2PSHIP_CONF_LOG_FILE);
	}

#ifdef CONFIG_START_GLIB_MAIN_LOOP
	if (!g_thread_supported())
		g_thread_init(NULL);
#endif
#ifdef CONFIG_START_GTK
	gdk_threads_init();
	gdk_threads_enter();
	gtk_init(&argc, &argv);
#endif

#ifdef CALL_DEBUG
	calldebug_init();
#endif
	/* mark starttime for uptime calcs */
	time(&p2pship_start);

	/* register each modules */
	ASSERT_ZERO(processor_init(config), err);
#ifdef CONFIG_HIP_ENABLED
	hipapi_register();
#endif
#ifdef CONFIG_SIP_ENABLED
	sipp_register();
#endif
	ident_addr_register();
	ident_register();
#ifdef CONFIG_WEBCONF_ENABLED
	webconf_register();
#endif
#ifdef CONFIG_EXTAPI_ENABLED
	extapi_register();
#endif
#ifdef CONFIG_WEBCACHE_ENABLED
	webcache_register();
#endif
	resourceman_register();
	olclient_register();
	conn_register();
	netio_register();
	netio_events_register();
	netio_ff_register();
	netio_man_register();
	netio_http_register();
	ui_register();
	ui_stdin_register();
	processor_init_module("ui_stdin", config);
	
#ifdef CONFIG_DBUS_ENABLED
	dbus_register();
#endif

	if (!console_only) {
#ifdef CONFIG_GTKUI_ENABLED
		ui_gtk_register();
		processor_init_module("ui_gtk", config);
#endif
	}
	addrbook_register();
#ifdef CONFIG_PYTHON_ENABLED
	pymod_register();	
#endif

#ifdef CONFIG_MEDIA_ENABLED
	media_register();
#endif
	/* check what we actually should do */
	switch (action) {
	case ACTION_LIST_CA: { /* list ca */
		if (processor_init_module("ident", config)) {
			USER_ERROR("Error initializing system\n");
		} else {
			ident_data_print_cas(ident_get_cas());
		}
		break;
	}

	case ACTION_REMOVE_CA: { /* remove ca */
		if (processor_init_module("ident", config)) {
			USER_ERROR("Error initializing system\n");
		} else {
			ident_remove_ca(action_param);
		}
		break;
	}

	case ACTION_LIST: { /* list */
		if (processor_init_module("ident", config)) {
			USER_ERROR("Error initializing system\n");
		} else {
			ident_data_print_idents(ident_get_identities());
		}
		break;
	}

	case ACTION_REMOVE: { /* remove */
		if (processor_init_module("ident", config)) {
			USER_ERROR("Error initializing system\n");
		} else {
			ident_remove_ident(action_param);
		}
		break;
	}

	case ACTION_IMPORT:  /* import */
	case ACTION_IMPORT_CA: { /* import ca */
		if (processor_init_module("ident", config)) {
			USER_ERROR("Error initializing system\n");
		} else {
			if (ident_import_file(action_param, 1)) {
				USER_ERROR("Error loading processing file %s\n", action_param);
			}
		}
		break;
	}
		
#ifdef CONFIG_HIP_ENABLED
	case ACTION_LIST_HITS: {
		if (processor_init_module("hipapi", config)) {
			USER_ERROR("Error initializing system\n");
		} else {
			hipapi_list_hits();
		}
		break;
	}
#endif
	case ACTION_NONE:
	default: {
		struct rlimit rl;
		int result;
		
#ifdef CONFIG_PYTHON_ENABLED
		if (processor_config_is_true(config, P2PSHIP_CONF_START_SHELL))
			processor_config_set_false(config, P2PSHIP_CONF_DAEMON);
#endif
		/* go daemon (..whee!) */
		if (processor_config_is_true(config, P2PSHIP_CONF_DAEMON)) {
			if (fork())
				goto err;			
		}
		
		/* check the stack size */
		if (!(result = getrlimit(RLIMIT_STACK, &rl))) {
			const rlim_t stacksize = 32L * 1024L * 1024L;
			if (rl.rlim_cur < stacksize) {
				LOG_INFO("increasing stack size to %d\n", stacksize);
				rl.rlim_cur = stacksize;
				if (setrlimit(RLIMIT_STACK, &rl)) {
					LOG_ERROR("could not set new stack size!\n");
				}
			}
		} else {
			LOG_ERROR("error checking stack size\n");
		}

		if (processor_init_modules(config) ||
		    (load_autoreg && ident_autoreg_load())) {
			USER_ERROR("Error initializing system\n");
		} else {
#ifdef REMOTE_DEBUG
			ship_remote_debug_init(config);
#endif
			/* start the main loop, blocks */
#ifdef REF_DEBUG2
			//			processor_tasks_add_periodic(ship_debug_reportref, 10000);
#endif

			if (do_test) {
				LOG_DEBUG("Run tests..\n");
			}

			processor_run();
		}
	}
	}
        
	ret = 0;
 err:
#ifdef REF_DEBUG2
	ship_debug_reportref();
#endif
	processor_close();
	freez(action_param);
	processor_config_free(config);
	processor_config_free(config2);

#ifdef LOCK_DEBUG
	debug2_close();
#endif
#ifdef REF_DEBUG2
	ship_debug_closeref();
#endif

	xmlCleanupThreads();
        if (!ret && !flag_quiet)
                USER_ERROR("ending ok\n");

	processor_cleanup_pid();
        return ret;
}
Beispiel #26
0
void xml_value(	const char	*xmlBuf,
       		const char	*elementName, 
       		int 		elementNumber, 
		const char	*childName,
		int		childNumber,
		char		**value,
       		int		*iret )
/************************************************************************
 * xml_value                                                            *
 *                                                                      *
 * This function returns the value of the specified element that is     *
 * contained in an xml file.   						*
 * 									*
 * The input element is actually part of an XPath expression.  This     *
 * expression by default assumes the searched for element is a child    *
 * of the root node of the xml document (/root/elementName).  The root  *
 * node should not be specified in elementName, however.  This routine  *
 * will prepend "[slash]*[slash]" to the beginning of the element name, *
 * thus always matching the root.					* 
 *                                                                      *
 * See additional documentation and usage examples of this and other    *
 * cgemlib/xml library routines at:					*
 *									*
 *	$NAWIPS/doc/Prog_guid/xml/cgemlibxml.sxw.			*
 *									*
 *                                                                      *
 * int xml_value( xmlBuf, elementName, elementNumber, childName,        *
 *			childNumber, value, iret ) 			*
 *                                                                      *
 * Input parameters:                                                    *
 *      *xmlBuf		const char	buffer containing xml document  *
 *	*elementName	const char	element name to be counted	* 
 *	elementNumber 	int       	element number or 0         	*
 *      *childName   	const char	name of child element or NULL   *
 *	childNumber 	int       	child number or 0          	*
 *                                                                      *
 * Output parameters:                                                   *
 *	**value		char		value of element (calling 	*
 *					  routine must free memory)	*
 *      *iret           int             Return code                     *
 *					  1 = non-fatal xpath error     *
 *					       see Valid Inputs above   *
 *                                        0 = normal                    *
 *                                       -1 = bad xmlBuf pointer (NULL) *
 *                                       -2 = bufSize <= 0              *
 *					 -3 = fatal error creating      *
 *					       XPath expression		*
 *					-15 = error executing xpath expr*
 *                                       -9 = node list is empty        *
 *                                      -16 = xpath expr returned more  *
 *						than one node		*
 *					 -9 = selected node is empty	*
 **                                                                     *
 * Log:                                                                 *
 * E. Safford/SAIC	11/05	initial coding (adapted from tutorial   *
 *				 by Aleksey Sanin, Copyright 2004, used *
 *                               under GNU Free Documentation License)  *
 * E. Safford/SAIC	04/06	correct error codes with xml.err	*
 ***********************************************************************/
{
    int 		ier, bufSize = 0, size = 0;
    xmlChar		*xpathExpr = NULL;
    xmlXPathObjectPtr	xpathObj;
    xmlNodeSetPtr	nodes;
    xmlNodePtr 		curNode;
    xmlDocPtr 		doc; 

 /*--------------------------------------------------------------------*/

    *iret = 0;

    /*
     *  sanity check on parameters
     */ 
    if( xmlBuf == NULL ) {
	*iret = -1;
	return;
    }
    
    bufSize = strlen( xmlBuf );

    if( bufSize <= 0 ) {
	*iret = -2;
	return;
    }


    /* 
     * Init libxml 
     */
    xmlInitParser();


    /*
     * Make the xpath expression
     */
    xml_makeXpathExpr( elementName, elementNumber, childName, 
    		       childNumber, NULL, &xpathExpr, &ier );

    if( ier < 0 ) {
	*iret = -3;
	G_FREE( xpathExpr, xmlChar );
	return;
    }
    else if( ier > 0 ) {
	*iret = 1;
    }


    xml_executeXpathExpr( xmlBuf, bufSize, xpathExpr, &doc, &xpathObj, &ier );
    if( ier != 0 ) {
        *iret = -15;
    }
    else {
        nodes = xpathObj->nodesetval;
        if( nodes ) {
            size = nodes->nodeNr;
        }


        /*
         *  Size indicates the number of nodes returned from the XPath 
	 *  expression.  This should be 1 and only 1; both 0 and > 1 are 
	 *  errors.  0 means the XPath expression didn't match anything, 
	 *  and > 1 means it matched too many things and we can't identify
	 *  a unique value to return.
         */
        if( size <= 0 ) {
	    *iret = -9;
        }

        if( size > 1 ) {
	    *iret = -16;
        }
    }


    if( *iret >= 0 ) {

        /*
         *  Return the content of the node.  This must be an XML_TEXT_NODE and 
	 *  it must have non-NULL content.  Any other condition is an error.
         */
        curNode = nodes->nodeTab[0];

        if( curNode->type == XML_ELEMENT_NODE ) {
	    curNode= curNode->children;
        }

	if( ( curNode->type == XML_TEXT_NODE ) && curNode->content ) {
	    *value = malloc( (strlen( (char *)(curNode->content) ) + 1) * 
	    			sizeof( char ));
	    strcpy( *value, (char *)curNode->content );
        }
        else {
	    *iret = -9;
        }
    }

    /* 
     * Shutdown libxml and clean up
     */
    xmlCleanupParser();
    G_FREE( xpathExpr, xmlChar );

    xmlXPathFreeObject( xpathObj );
    xmlFreeDoc( doc ); 
    
    return;
}
Beispiel #27
0
void xml_parser_init(void)
{
	xmlKeepBlanksDefault(0);
	xmlInitParser();
}
/**
 * htmlNodeDump:
 * @buf:  the HTML buffer output
 * @doc:  the document
 * @cur:  the current node
 *
 * Dump an HTML node, recursive behaviour,children are printed too,
 * and formatting returns are added.
 *
 * Returns the number of byte written or -1 in case of error
 */
int
htmlNodeDump(xmlBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur) {
    xmlInitParser();

    return(htmlNodeDumpFormat(buf, doc, cur, 1));
}
Beispiel #29
0
void Init_nokogiri()
{
#ifndef __MACRUBY__
  xmlMemSetup(
      (xmlFreeFunc)ruby_xfree,
      (xmlMallocFunc)ruby_xmalloc,
      (xmlReallocFunc)ruby_xrealloc,
      ruby_strdup
  );
#endif

  mNokogiri         = rb_define_module("Nokogiri");
  mNokogiriXml      = rb_define_module_under(mNokogiri, "XML");
  mNokogiriHtml     = rb_define_module_under(mNokogiri, "HTML");
  mNokogiriXslt     = rb_define_module_under(mNokogiri, "XSLT");
  mNokogiriXmlSax   = rb_define_module_under(mNokogiriXml, "SAX");
  mNokogiriHtmlSax  = rb_define_module_under(mNokogiriHtml, "SAX");

  rb_const_set( mNokogiri,
                rb_intern("LIBXML_VERSION"),
                NOKOGIRI_STR_NEW2(LIBXML_DOTTED_VERSION)
              );
  rb_const_set( mNokogiri,
                rb_intern("LIBXML_PARSER_VERSION"),
                NOKOGIRI_STR_NEW2(xmlParserVersion)
              );

#ifdef LIBXML_ICONV_ENABLED
  rb_const_set(mNokogiri, rb_intern("LIBXML_ICONV_ENABLED"), Qtrue);
#else
  rb_const_set(mNokogiri, rb_intern("LIBXML_ICONV_ENABLED"), Qfalse);
#endif

  xmlInitParser();

  init_xml_document();
  init_html_document();
  init_xml_node();
  init_xml_document_fragment();
  init_xml_text();
  init_xml_cdata();
  init_xml_processing_instruction();
  init_xml_attr();
  init_xml_entity_reference();
  init_xml_comment();
  init_xml_node_set();
  init_xml_xpath_context();
  init_xml_sax_parser_context();
  init_xml_sax_parser();
  init_xml_sax_push_parser();
  init_xml_reader();
  init_xml_dtd();
  init_xml_element_content();
  init_xml_attribute_decl();
  init_xml_element_decl();
  init_xml_entity_decl();
  init_xml_namespace();
  init_html_sax_parser_context();
  init_html_sax_push_parser();
  init_xslt_stylesheet();
  init_xml_syntax_error();
  init_html_entity_lookup();
  init_html_element_description();
  init_xml_schema();
  init_xml_relax_ng();
  init_nokogiri_io();
  init_xml_encoding_handler();
}
Beispiel #30
0
/*****************************************************************************
 函 数 名  : subdesc_load
 功能描述  : 将sub文件转换为SUB_ROOT结构
 输入参数  : filename sub文件路径 desc, 将返回为SUB_ROOT分配的内存指针,
             *desc需要使用subdesc_free是否内存
 输出参数  : 无
 返 回 值  : ERROR_SUCCESS 成功 其他失败
 调用函数  :
 被调函数  :
 ============================================================================
 修改历史      :
  1.日    期   : 2008年8月26日
    
    修改内容   : 新生成函数

*****************************************************************************/
int subdesc_load(const char * filename, SUB_ROOT ** desc)
{
    int ret = ERROR_SUCCESS;
    xmlDocPtr doc;

    /* Init libxml */
    xmlInitParser();
    LIBXML_TEST_VERSION

    assert(filename);

    //为root分配内存
    *desc = (SUB_ROOT *)malloc(sizeof(SUB_ROOT));
    if(NULL == *desc)
    {
        return ERROR_SYSTEM;
    }
    memset(*desc, 0, sizeof(SUB_ROOT));

    //为哈西结构分配内存
    (*desc)->_hashtable = malloc(sizeof(struct hsearch_data));
    if(NULL == (*desc)->_hashtable)
    {
        subdesc_free(*desc);
        *desc = NULL;
        return ERROR_SYSTEM;
    }
    memset((*desc)->_hashtable, 0, sizeof(struct hsearch_data));

    /* Load XML document */
    doc = xmlParseFile(filename);
    if (doc == NULL)
    {
        subdesc_free(*desc);
        *desc = NULL;
        http_out("Invalid sub file.");
        return ERROR_SYSTEM;
    }

    if(ERROR_SUCCESS == ret)
    {
        /*初试化哈西表*/
        ret = subdesc_create_hashtable(doc, *desc);
    }

    if(ERROR_SUCCESS == ret)
    {
        /*分析根元素*/
        ret = subdesc_ana_root(doc, *desc);
    }

    /* Cleanup */
    xmlFreeDoc(doc);

    /* Shutdown libxml */
    xmlCleanupParser();

    /*
     * this is to debug memory for regression tests
     */
    xmlMemoryDump();

    return ERROR_SUCCESS;
}