Exemplo n.º 1
0
Arquivo: grafo.c Projeto: gvs11/BCC
grafo le_grafo(FILE *input) {
    int i;
    Agnode_t *v;
    Agedge_t *a;
    Agraph_t *g_cgraph;

    g_cgraph = agread(input, NULL);

    if ( !g_cgraph )
        return NULL;

    // Cria grafo
    grafo g = (grafo) malloc(sizeof(struct grafo));
    g->tipo = agisdirected(g_cgraph);
    g->vertice = (vertice_t) malloc(agnnodes(g_cgraph) * sizeof(struct vertice_t));
    //Copia nome do grafo
    g->nome = (char *) malloc(strlen(agnameof(g_cgraph))+1);
    strcpy(g->nome, agnameof(g_cgraph));

    if (!g->vertice)
        return NULL;


    i = 0;
    // Copia vertices
    for (v=agfstnode(g_cgraph ); v; v=agnxtnode(g_cgraph ,v), i++) {
        // copia nome
        g->vertice[i].nome = (char *) malloc(strlen(agnameof(v))+1);
        strcpy(g->vertice[i].nome, agnameof(v));

	// inicializa lista de arestas
	g->vertice[i].aresta = NULL;
	// seta next vertice
	if (i != agnnodes(g_cgraph) - 1)
		g->vertice[i].next = &g->vertice[i+1];

        //set atribute
        Agnodeinfo_t *p;
        p = (Agnodeinfo_t*) agbindrec(v,"Agnodeinfo_t",sizeof(Agnodeinfo_t),TRUE);
        p->ref_v = &g->vertice[i];

    }
    g->vertice[i-1].next = NULL;

    //Copia arestas
    i = 0;
    for (v=agfstnode(g_cgraph); v; v=agnxtnode(g_cgraph,v), i++) {
        if (g->tipo == NAODIRECIONADO){
            for (a=agfstedge(g_cgraph,v); a; a=agnxtedge(g_cgraph,a,v))
                add_aresta(g, &g->vertice[i], v, a);
        } else {
            for (a=agfstout(g_cgraph,v); a; a=agnxtout(g_cgraph,a))
                add_aresta(g, &g->vertice[i], v, a);
        }
    }

    free(g_cgraph);
    return g;

}
Exemplo n.º 2
0
grafo le_grafo(FILE *input){
	if (!input)
		return NULL;
	
	Agraph_t *Ag = agread(input, NULL);
	
	if(!Ag)
		return NULL;

	grafo g = cria_grafo(agnameof(Ag), agisdirected(Ag), contem_pesos(Ag), agnnodes(Ag));

	for (Agnode_t *Av=agfstnode(Ag); Av; Av=agnxtnode(Ag,Av)) {
        	cria_vertice(g, agnameof(Av));
	}

    	for (Agnode_t *Av=agfstnode(Ag); Av; Av=agnxtnode(Ag,Av)) {
       		for (Agedge_t *Ae=agfstout(Ag,Av); Ae; Ae=agnxtout(Ag,Ae)) {
           		vertice u = v_busca(g, agnameof(agtail(Ae)));
           		vertice v = v_busca(g, agnameof(aghead(Ae)));
           		cria_vizinhanca(g, u, v, get_peso(Ae));
       		}
    	}
	
	agclose(Ag);
	agfree(Ag, NULL);
	return g;
}  
Exemplo n.º 3
0
int main(int argc, char* argv[])
{
	struct marsopts opts = init(argc, argv);
	Agraph_t* g = agread(opts.fin, (Agdisc_t*)NULL);
	Agnode_t* n;
	mat z;
	
	init_graph(g);
	z = mars(g, opts);
	mat_scalar_mult(z, opts.scale);

    if(opts.viewer) {
        viewer(argc, argv);
    } else {
	    for(n = agfstnode(g); n; n = agnxtnode(g,n)) {
		    int id = getid(n);
		    char* s = pos_to_str(&z->m[mindex(id, 0, z)], z->c);
		    agset(n,"pos",s);
		    free(s);
	    }
	
	    agwrite(g, opts.fout);
	}
	mat_free(z);
	clean_up(g);
	agclose(g);
	return 0;
}
Exemplo n.º 4
0
int main(int argc, char* argv[])
{
	if(argc != 3)
		usage();
	float scale = atof(argv[1]);
	FILE* fin = fopen(argv[2],"r");
	Agraph_t* g = agread(fin, (Agdisc_t*)NULL);
	Agnode_t* n;
	
	for(n = agfstnode(g); n; n = agnxtnode(g,n)) {
		char* pos = agget(n,"pos");
		double x,y;
		sscanf(pos,"%lf,%lf",&x,&y);
		x *= scale;
		y *= scale;		
		char* s = pos_to_str(x,y);
		agset(n,"pos",s);
		free(s);
	}
	
	agwrite(g,stdout);
	
	agclose(g);
	return 0;
}
Exemplo n.º 5
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d D O T I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadDOTImage() reads a Graphviz image file and returns it.  It allocates
%  the memory necessary for the new Image structure and returns a pointer to
%  the new image.
%
%  The format of the ReadDOTImage method is:
%
%      Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  char
    command[MaxTextExtent];

  const char
    *option;

  graph_t
    *graph;

  Image
    *image;

  ImageInfo
    *read_info;

  MagickBooleanType
    status;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    return((Image *) NULL);
  read_info=CloneImageInfo(image_info);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  (void) CopyMagickString(read_info->magick,"SVG",MaxTextExtent);
  (void) AcquireUniqueFilename(read_info->filename);
  (void) FormatLocaleString(command,MaxTextExtent,"-Tsvg -o%s %s",
    read_info->filename,image_info->filename);
  graph=agread(GetBlobFileHandle(image));
  if (graph == (graph_t *) NULL)
    return ((Image *) NULL);
  option=GetImageOption(image_info,"dot:layout-engine");
  if (option == (const char *) NULL)
    gvLayout(graphic_context,graph,(char *) "dot");
  else
    gvLayout(graphic_context,graph,(char *) option);
  gvRenderFilename(graphic_context,graph,(char *) "svg",read_info->filename);
  gvFreeLayout(graphic_context,graph);
  /*
    Read SVG graph.
  */
  image=ReadImage(read_info,exception);
  (void) RelinquishUniqueFileResource(read_info->filename);
  read_info=DestroyImageInfo(read_info);
  if (image == (Image *) NULL)
    return((Image *) NULL);
  return(GetFirstImageInList(image));
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
    Agraph_t *g;
    Agnode_t *n;
    int rv = 0;

    init(argc, argv);

    if ((g = agread(inFile)) != 0) {
	if (AG_IS_DIRECTED(g)) {
	    for (n = agfstnode(g); n; n = agnxtnode(g, n)) {
		if (ND_mark(n) == 0)
		    rv |= dfs(g, n, 0);
	    }
	    if (doWrite) {
		agwrite(g, outFile);
		fflush(outFile);
	    }
	    if (Verbose) {
		if (rv)
		    fprintf(stderr, "Graph %s has cycles\n", g->name);
		else
		    fprintf(stderr, "Graph %s is acyclic\n", g->name);
	    }
	} else {
	    rv = 2;
	    if (Verbose)
		fprintf(stderr, "Graph %s is undirected\n", g->name);
	}
	exit(rv);
    } else
	exit(-1);
}
int main() {
  FILE * fp = fopen("test", "r");
  assert(fp);
  Agraph_t * graph = agread(fp, NULL);
  assert(graph);
  printf("Number of nodes is %d\n", agnnodes(graph));
  printf("Number of edges is %d\n", agnedges(graph));

  /* Iterate through nodes */
  Agnode_t * node = agfstnode(graph);
  while (node != NULL) {
    assert(node);
    printf("Iterating through yet another node\n");
    char  * label = agget(node, "label");
    printf("Node label is %s\n", label);
    Agedge_t * edge   = agfstout(graph, node);
    while (edge != NULL) {
      assert(edge);
      printf("Iterating through yet another edge \n");
      assert(agtail(edge) == node);
      edge = agnxtout(graph, edge);
    }

    /* Move on to the next node */
    printf("\n");
    node  = agnxtnode(graph, node);
  }

  /* Free graph structure */
  agclose(graph);

  return 0;
}
Exemplo n.º 8
0
int main(int argc, char *argv[])
{
    Agraph_t *g;
    Agnode_t *n;
    int rv = 0;

    init(argc, argv);

    if ((g = agread(inFile,  (Agdisc_t *) 0)) != 0) {
	if (agisdirected (g)) {
	    aginit(g, AGNODE, "info", sizeof(Agnodeinfo_t), TRUE);
	    for (n = agfstnode(g); n; n = agnxtnode(g, n)) {
		if (ND_mark(n) == 0)
		    rv |= dfs(g, n, 0);
	    }
	    if (doWrite) {
		agwrite(g, outFile);
		fflush(outFile);
	    }
	    if (Verbose) {
		if (rv)
		    fprintf(stderr, "Graph \"%s\" has cycles; %d reversed edges\n", graphName(g), num_rev);
		else
		    fprintf(stderr, "Graph \"%s\" is acyclic\n", graphName(g));
	    }
	} else {
	    rv = -1;
	    if (Verbose)
		fprintf(stderr, "Graph \"%s\" is undirected\n", graphName(g));
	}
	exit(rv);
    } else
	exit(-1);
}
void LoadAGraphThread::run()
{
  kDebug() << m_dotFileName;
  GVC_t *gvc;
  FILE* fp;
  gvc = gvContext();
  fp = fopen(m_dotFileName.toUtf8().data(), "r");
  m_g = agread(fp);
}
Exemplo n.º 10
0
//------------------------------------------------------------------------------
int main(void) {

  Agraph_t *g = agread(stdin, NULL);

  if ( !g )
    return 1;

  agclose(mostra_grafo(g));

  return agerrors();
}
Exemplo n.º 11
0
Agraph_t *read(char *filename)
{
    FILE *f;
    Agraph_t *g;

    f = fopen(filename, "r");
    if (!f)
	return NULL;
    g = agread(f);
    fclose(f);
    return g;
}
Exemplo n.º 12
0
/**
 *  \brief Open a graph from a dot file and create a graph structure
 *  \param filename The path to the dot file to load.
 *  \return A pointer to the created graph structure.
 */
Agraph_t* graph__open(char * filename){
     FILE * fd = fopen(filename, "r");
     if(fd == NULL){
	  perror("fopen");
	  return NULL;
     }

     Agraph_t *g = agread(fd);
     fclose(fd);

     return g;
}
Exemplo n.º 13
0
Agraph_t *read(const char *filename)
{
    FILE *f;
    Agraph_t *g;

    f = fopen(filename, "r");
    if (!f)
        return NULL;
    if (!gvc)
        gv_init();
    g = agread(f, NULL);
    fclose(f);
    return g;
}
Exemplo n.º 14
0
graph_t* next_input_graph(void)
{
	graph_t		*g;
	static FILE	*fp;

	if (fp == NULL) fp = next_input_file();
	g = NULL;

	while (fp != NULL) {
		if ((g = agread(fp))) break;
		fp = next_input_file();
	}
	return g;
}
Exemplo n.º 15
0
int main(int argc, char **argv)
{
    Agraph_t *g;
    Agnode_t *u, *v;
	int rv;

	g = agread(stdin,0);
	if (argc >= 3) {
		u = agnode(g,argv[1],FALSE);
		v = agnode(g,argv[2],FALSE);
		rv = agnodebefore(u,v);
		fprintf(stderr,"agnodebefore returns %d\n",rv);
		fprintf(stderr,"dtsize %d\n",dtsize(g->n_seq));
	}
	agwrite(g,stdout);
}
Exemplo n.º 16
0
graph_t *gvNextInputGraph(GVC_t *gvc)
{
    graph_t *g = NULL;
    static char *fn;
    static FILE *fp;
    static int fidx, gidx;
    GVG_t *gvg;

    while (!g) {
	if (!fp) {
    	    if (!(fn = gvc->input_filenames[0])) {
		if (fidx++ == 0)
		    fp = stdin;
	    }
	    else {
		while ((fn = gvc->input_filenames[fidx++]) && !(fp = fopen(fn, "r")))  {
		    agerr(AGERR, "%s: can't open %s\n", gvc->common.cmdname, fn);
		    graphviz_errors++;
		}
	    }
	}
	if (fp == NULL)
	    break;
	agsetfile(fn ? fn : "<stdin>");
#ifdef EXPERIMENTAL_MYFGETS
	g = agread_usergets(fp, myfgets);
#else
	g = agread(fp);
#endif
	if (g) {
	    gvg = zmalloc(sizeof(GVG_t));
	    if (!gvc->gvgs) 
		gvc->gvgs = gvg;
	    else
		gvc->gvg->next = gvg;
	    gvc->gvg = gvg;
	    gvg->gvc = gvc;
	    gvg->g = g;
	    gvg->input_filename = fn;
	    gvg->graph_index = gidx++;
	    break;
	}
	fp = NULL;
	gidx = 0;
    }
    return g;
}
Exemplo n.º 17
0
//------------------------------------------------------------------------------
grafo le_grafo(FILE *input) {
  Agraph_t *g;
  grafo grafo_lido;
  char peso_string[] = "peso";

  /* Aloca estrutura do grafo lido */
  grafo_lido = (grafo) malloc(sizeof(struct grafo));

  if(grafo_lido != NULL) {
    /* Armazena em g o grafo lido da entrada */
    if((g = agread(input, NULL)) == NULL) {
      destroi_grafo(grafo_lido);
      return NULL;
    }

    /* Carrega na estrutura os vértices de g */
    if((grafo_lido->grafo_vertices = obter_vertices(g, &(grafo_lido->grafo_n_vertices))) == NULL) {
      agclose(g);
      destroi_grafo(grafo_lido);
      return NULL;
    }

    /* Verifica se g é um grafo ponderado ou não */
    if(agattr(g, AGEDGE, peso_string, (char *) NULL) != NULL) {
      grafo_lido->grafo_ponderado = 1;
    } else {
      grafo_lido->grafo_ponderado = 0;
    }
    
    /* Define o nome do grafo e se ele é direcionado */
    grafo_lido->grafo_direcionado = agisdirected(g);
    grafo_lido->grafo_nome = strdup(agnameof(g));

    /* Carrega na estrutura a matriz de adjacência de g */
    if((grafo_lido->grafo_matriz = obter_matriz_adjacencia(g, grafo_lido->grafo_vertices, grafo_lido->grafo_ponderado, grafo_lido->grafo_direcionado, grafo_lido->grafo_n_vertices)) == NULL) {
      agclose(g);
      destroi_grafo(grafo_lido);
      return NULL;
    }

    agclose(g);
  }

  return grafo_lido;
}
Exemplo n.º 18
0
int main (int argc, char* argv[])
{
    graph_t *g;
    graph_t *sg;
    FILE *fp;
    graph_t** cc;
    int       i, ncc;
    GVC_t *gvc;

    gvc = gvContext();

    if (argc > 1)
        fp = fopen(argv[1], "r");
    else
        fp = stdin;
    g = agread(fp, 0);

    cc = ccomps(g, &ncc, (char*)0);

    for (i = 0; i < ncc; i++) {
        sg = cc[i];
        nodeInduce (sg);
        gvLayout(gvc, sg, "neato");
    }
    pack_graph (ncc, cc, g, 0);

    gvRender(gvc, g, "ps", stdout);

    for (i = 0; i < ncc; i++) {
        sg = cc[i];
        gvFreeLayout(gvc, sg);
        agdelete(g, sg);
    }

    agclose(g);

    return (gvFreeContext(gvc));

}
Exemplo n.º 19
0
void*
AI_alert_correlation_thread ( void *arg )
{
	int                       i;
	struct stat               st;

	char                      corr_dot_file[4096]   = { 0 };

#ifdef HAVE_LIBGVC
	char                      corr_ps_file [4096]   = { 0 };
#endif

	double                    avg_correlation       = 0.0,
						 std_deviation         = 0.0,
						 corr_threshold        = 0.0,
						 kb_correlation        = 0.0,
						 bayesian_correlation  = 0.0,
						 neural_correlation    = 0.0;

	size_t                    n_correlations        = 0,
						 n_corr_functions      = 0,
						 n_corr_weights        = 0;

	FILE                      *fp                   = NULL;

	AI_alert_correlation_key  corr_key;
	AI_alert_correlation      *corr                 = NULL;

	AI_alert_type_pair_key    pair_key;
	AI_alert_type_pair        *pair                 = NULL,
						 *unpair               = NULL;

	AI_snort_alert            *alert_iterator       = NULL,
					      *alert_iterator2      = NULL;

	pthread_t                 manual_corr_thread;

	#ifdef                    HAVE_LIBGVC
	char                      corr_png_file[4096]   = { 0 };
	GVC_t                     *gvc                  = NULL;
	graph_t                   *g                    = NULL;
	#endif

	double (**corr_functions)( const AI_snort_alert*, const AI_snort_alert* ) = NULL;
	double (**corr_weights)() = NULL;

	#ifdef HAVE_LIBPYTHON2_6
	PyObject *pyA = NULL,
		    *pyB = NULL;

	PyObject *pArgs = NULL,
		    *pRet  = NULL;

	PyObject **py_corr_functions   = NULL;
	PyObject **py_weight_functions = NULL;

	size_t   n_py_corr_functions   = 0;
	size_t   n_py_weight_functions = 0;

	double   py_value  = 0.0,
		    py_weight = 0.0;

	py_corr_functions = AI_get_py_functions ( &n_py_corr_functions );
	py_weight_functions = AI_get_py_weights ( &n_py_weight_functions );
	#endif

	corr_functions = AI_get_corr_functions ( &n_corr_functions );
	corr_weights   = AI_get_corr_weights ( &n_corr_weights );

	pthread_mutex_init ( &mutex, NULL );

	/* Start the thread for parsing manual correlations from XML */
	if ( pthread_create ( &manual_corr_thread, NULL, AI_manual_correlations_parsing_thread, NULL ) != 0 )
	{
		AI_fatal_err ( "Failed to create the manual correlations parsing thread", __FILE__, __LINE__ );
	}

	while ( 1 )
	{
		sleep ( config->correlationGraphInterval );

		if ( stat ( config->corr_rules_dir, &st ) < 0 )
		{
			_dpd.errMsg ( "AIPreproc: Correlation rules directory '%s' not found, the correlation thread won't be active\n",
					config->corr_rules_dir );
			pthread_exit (( void* ) 0 );
			return ( void* ) 0;
		}

		/* Set the lock flag to true, and keep it this way until I've done with correlating alerts */
		pthread_mutex_lock ( &mutex );

		if ( alerts )
		{
			AI_free_alerts ( alerts );
			alerts = NULL;
		}

		if ( !( alerts = AI_get_clustered_alerts() ))
		{
			pthread_mutex_unlock ( &mutex );
			continue;
		}

		if ( config->use_knowledge_base_correlation_index != 0 )
		{
			AI_kb_index_init ( alerts );
		}

		__AI_correlation_table_cleanup();
		correlation_table = NULL;

		/* Fill the table of correlated alerts */
		for ( alert_iterator = alerts; alert_iterator; alert_iterator = alert_iterator->next )
		{
			for ( alert_iterator2 = alerts; alert_iterator2; alert_iterator2 = alert_iterator2->next )
			{
				if ( alert_iterator != alert_iterator2 && ! (
					alert_iterator->gid == alert_iterator2->gid &&
					alert_iterator->sid == alert_iterator2->sid &&
					alert_iterator->rev == alert_iterator2->rev ))
				{
					if ( !( corr = ( AI_alert_correlation* ) malloc ( sizeof ( AI_alert_correlation ))))
						AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );

					corr_key.a = alert_iterator;
					corr_key.b = alert_iterator2;
					corr->key  = corr_key;
					corr->correlation = 0.0;
					n_correlations = 0;

					kb_correlation = AI_kb_correlation_coefficient ( corr_key.a, corr_key.b );
					bayesian_correlation = AI_alert_bayesian_correlation ( corr_key.a, corr_key.b );
					neural_correlation = AI_alert_neural_som_correlation ( corr_key.a, corr_key.b );

					/* Use the correlation indexes for which we have a value */
					if ( bayesian_correlation != 0.0 && config->bayesianCorrelationInterval != 0 )
					{
						corr->correlation += AI_bayesian_correlation_weight() * bayesian_correlation;
						n_correlations++;
					}

					if ( kb_correlation != 0.0 && config->use_knowledge_base_correlation_index )
					{
						corr->correlation += kb_correlation;
						n_correlations++;
					}

					if ( neural_correlation != 0.0 && config->neuralNetworkTrainingInterval != 0 )
					{
						corr->correlation += AI_neural_correlation_weight() * neural_correlation;
						n_correlations++;
					}

					/* Get the correlation indexes from extra correlation modules */
					if (( corr_functions ))
					{
						for ( i=0; i < n_corr_functions; i++ )
						{
							if ( corr_weights[i]() != 0.0 )
							{
								corr->correlation += corr_weights[i]() * corr_functions[i] ( corr_key.a, corr_key.b );
								n_correlations++;
							}
						}
					}

					#ifdef HAVE_LIBPYTHON2_6
					if (( py_corr_functions ))
					{
						pyA = AI_alert_to_pyalert ( corr_key.a );
						pyB = AI_alert_to_pyalert ( corr_key.b );

						if ( pyA && pyB )
						{
							for ( i=0; i < n_py_corr_functions; i++ )
							{
								if ( !( pArgs = Py_BuildValue ( "(OO)", pyA, pyB )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not initialize the Python arguments for the call", __FILE__, __LINE__ );
								}

								if ( !( pRet = PyEval_CallObject ( py_corr_functions[i], pArgs )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not call the correlation function from the Python module", __FILE__, __LINE__ );
								}

								if ( !( PyArg_Parse ( pRet, "d", &py_value )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not parse the correlation value out of the Python correlation function", __FILE__, __LINE__ );
								}

								Py_DECREF ( pRet );
								Py_DECREF ( pArgs );

								if ( !( pRet = PyEval_CallObject ( py_weight_functions[i], (PyObject*) NULL )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not call the correlation function from the Python module", __FILE__, __LINE__ );
								}

								if ( !( PyArg_Parse ( pRet, "d", &py_weight )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not parse the correlation weight out of the Python correlation function", __FILE__, __LINE__ );
								}

								Py_DECREF ( pRet );

								if ( py_weight != 0.0 )
								{
									corr->correlation += py_weight * py_value;
									n_correlations++;
								}
							}

							Py_DECREF ( pyA ); Py_DECREF ( pyB );
							/* free ( pyA ); free ( pyB ); */
							pyA = NULL; pyB = NULL;
						}
					}
					#endif

					if ( n_correlations != 0 )
					{
						corr->correlation /= (double) n_correlations;
					}

					HASH_ADD ( hh, correlation_table, key, sizeof ( AI_alert_correlation_key ), corr );
				}
			}
		}

		if ( HASH_COUNT ( correlation_table ) > 0 )
		{
			avg_correlation = 0.0;
			std_deviation   = 0.0;

			/* Compute the average correlation coefficient */
			for ( corr = correlation_table; corr; corr = ( AI_alert_correlation* ) corr->hh.next )
			{
				avg_correlation += corr->correlation;
			}

			avg_correlation /= (double) HASH_COUNT ( correlation_table );

			/* Compute the standard deviation */
			for ( corr = correlation_table; corr; corr = ( AI_alert_correlation* ) corr->hh.next )
			{
				std_deviation += ( corr->correlation - avg_correlation ) * ( corr->correlation - avg_correlation );
			}

			std_deviation = sqrt ( std_deviation / (double) HASH_COUNT ( correlation_table ));
			corr_threshold = avg_correlation + ( config->correlationThresholdCoefficient * std_deviation );
			snprintf ( corr_dot_file, sizeof ( corr_dot_file ), "%s/correlated_alerts.dot", config->corr_alerts_dir );
			
			if ( stat ( config->corr_alerts_dir, &st ) < 0 )
			{
				if ( mkdir ( config->corr_alerts_dir, 0755 ) < 0 )
				{
					AI_fatal_err ( "Unable to create directory the correlated alerts directory", __FILE__, __LINE__ );
				}
			} else if ( !S_ISDIR ( st.st_mode )) {
				AI_fatal_err ( "The specified directory for correlated alerts is not a directory", __FILE__, __LINE__ );
			}

			if ( !( fp = fopen ( corr_dot_file, "w" )))
				AI_fatal_err ( "Could not write on the correlated alerts .dot file", __FILE__, __LINE__ );
			fprintf ( fp, "digraph G  {\n" );

			/* Find correlated alerts */
			for ( corr = correlation_table; corr; corr = ( AI_alert_correlation* ) corr->hh.next )
			{
				pair_key.from_sid = corr->key.a->sid;
				pair_key.from_gid = corr->key.a->gid;
				pair_key.from_rev = corr->key.a->rev;
				pair_key.to_sid = corr->key.b->sid;
				pair_key.to_gid = corr->key.b->gid;
				pair_key.to_rev = corr->key.b->rev;

				HASH_FIND ( hh, manual_correlations, &pair_key, sizeof ( pair_key ), pair );
				HASH_FIND ( hh, manual_uncorrelations, &pair_key, sizeof ( pair_key ), unpair );

				/* Yes, BlackLight wrote this line of code in a pair of minutes and immediately
				 * compiled it without a single error */
				if ( !unpair && ( pair || (
						corr->correlation >= corr_threshold &&
						corr_threshold != 0.0 &&
						corr->key.a->timestamp <= corr->key.b->timestamp && ! (
						corr->key.a->gid == corr->key.b->gid &&
						corr->key.a->sid == corr->key.b->sid &&
						corr->key.a->rev == corr->key.b->rev ) && (
							corr->key.a->ip_src_addr == corr->key.b->ip_src_addr || (
								(corr->key.a->h_node[src_addr] && corr->key.b->h_node[src_addr]) ?
									( corr->key.a->h_node[src_addr]->max_val == corr->key.b->h_node[src_addr]->max_val &&
									corr->key.a->h_node[src_addr]->min_val == corr->key.b->h_node[src_addr]->min_val ) : 0
							)) && (
							corr->key.a->ip_dst_addr == corr->key.b->ip_dst_addr || (
								(corr->key.a->h_node[dst_addr] && corr->key.b->h_node[dst_addr]) ?
									( corr->key.a->h_node[dst_addr]->max_val == corr->key.b->h_node[dst_addr]->max_val &&
									corr->key.a->h_node[dst_addr]->min_val == corr->key.b->h_node[dst_addr]->min_val ) : 0
							))
						)
					)
				)  {
					if ( !( corr->key.a->derived_alerts = ( AI_snort_alert** ) realloc ( corr->key.a->derived_alerts,
									(++corr->key.a->n_derived_alerts) * sizeof ( AI_snort_alert* ))))
						AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );

					if ( !( corr->key.b->parent_alerts = ( AI_snort_alert** ) realloc ( corr->key.b->parent_alerts,
									(++corr->key.b->n_parent_alerts) * sizeof ( AI_snort_alert* ))))
						AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );

					corr->key.a->derived_alerts[ corr->key.a->n_derived_alerts - 1 ] = corr->key.b;
					corr->key.b->parent_alerts [ corr->key.b->n_parent_alerts  - 1 ] = corr->key.a;
					__AI_correlated_alerts_to_dot ( corr, fp );

					if ( config->outdbtype != outdb_none )
					{
						AI_store_correlation_to_db ( corr );
					}
				}
			}

			fprintf ( fp, "}\n" );
			fclose ( fp );

			#ifdef HAVE_LIBGVC
				snprintf ( corr_png_file, sizeof ( corr_png_file ), "%s/correlated_alerts.png", config->corr_alerts_dir );
				snprintf ( corr_ps_file , sizeof ( corr_ps_file  ), "%s/correlated_alerts.ps" , config->corr_alerts_dir );

				if ( !( gvc = gvContext() ))
				{
					pthread_mutex_unlock ( &mutex );
					continue;
				}

				if ( !( fp = fopen ( corr_dot_file, "r" )))
				{
					pthread_mutex_unlock ( &mutex );
					continue;
				}

				if ( !( g = agread ( fp )))
				{
					pthread_mutex_unlock ( &mutex );
					continue;
				}

				gvLayout ( gvc, g, "dot" );
				gvRenderFilename ( gvc, g, "png", corr_png_file );
				gvRenderFilename ( gvc, g, "ps" , corr_ps_file  );

				gvFreeLayout ( gvc, g );
				agclose ( g );
				fclose ( fp );
			#endif

			/* If no database output is defined, then the alerts have no alert_id, so we cannot use the
			 * web interface for correlating them, as they have no unique identifier */
			if ( config->outdbtype != outdb_none )
			{
				if ( strlen ( config->webserv_dir ) != 0 )
				{
					__AI_correlated_alerts_to_json ();
				}
			}
		}

		pthread_mutex_unlock ( &mutex );
	}

	pthread_exit (( void* ) 0 );
	return (void*) 0;
}		/* -----  end of function AI_alert_correlation_thread  ----- */
Exemplo n.º 20
0
Agraph_t *read(FILE *f)
{
    if (!gvc)
        gv_init();
    return agread(f, NULL);
}
Exemplo n.º 21
0
Agraph_t *read(FILE *f)
{
    if (!gvc)
	gvc = gvContext();
    return agread(f);
}
Exemplo n.º 22
0
Arquivo: utils.c Projeto: lccanon/ggen
int ggen_read_graph(igraph_t *g,FILE *input)
{
	Agraph_t *cg;
	Agnode_t *v;
	Agedge_t *e;
	igraph_vector_t edges;
	igraph_vector_t vertices;
	int err;
	unsigned long esize;
	unsigned long vsize;
	unsigned long from, to;
	igraph_integer_t eid;
	Agsym_t *att;

	/* read the graph */
	cg = agread((void *)input,NULL);
	if(!cg) return 1;

	if(!agisdirected(cg))
	{
		error("Input graph is undirected\n");
		err = 1;
		goto error_d;
	}

	/* init edge array */
	err = igraph_vector_init(&edges,2*agnedges(cg));
	if(err) goto error_d;

	err = igraph_vector_init(&vertices,agnnodes(cg));
	if(err) goto error_de;

	/* init igraph */
	igraph_empty(g,agnnodes(cg),1);

	/* asign id to each vertex */
	vsize = 0;
	for(v = agfstnode(cg); v; v = agnxtnode(cg,v))
		VECTOR(vertices)[vsize++] = AGID(v);

	/* loop through each edge */
	esize = 0;
	for(v = agfstnode(cg); v; v = agnxtnode(cg,v))
	{
		from = find_id(AGID(v),vertices,vsize);
		for(e = agfstout(cg,v); e; e = agnxtout(cg,e))
		{
			to = find_id(AGID(aghead(e)),vertices,vsize);
			VECTOR(edges)[esize++] = from;
			VECTOR(edges)[esize++] = to;
		}
	}

	/* finish the igraph */
	err = igraph_add_edges(g,&edges,NULL);
	if(err) goto error;

	/* read graph properties */
	att = agnxtattr(cg,AGRAPH,NULL);
	while(att != NULL)
	{
		/* copy this attribute to igraph */
		SETGAS(g,att->name,agxget(cg,att));
		att = agnxtattr(cg,AGRAPH,att);
	}
	/* we keep the graph name using a special attribute */
	SETGAS(g,GGEN_GRAPH_NAME_ATTR,agnameof(cg));

	/* read vertex properties */
	att = agnxtattr(cg,AGNODE,NULL);
	while(att != NULL)
	{
		/* iterate over all vertices for this attribute */
		for(v = agfstnode(cg); v; v = agnxtnode(cg,v))
		{
			from = find_id(AGID(v),vertices,vsize);
			SETVAS(g,att->name,from,agxget(v,att));
		}
		att = agnxtattr(cg,AGNODE,att);
	}
	/* we keep each vertex name in a special attribute */
	for(v = agfstnode(cg); v; v = agnxtnode(cg,v))
	{
			from = find_id(AGID(v),vertices,vsize);
			SETVAS(g,GGEN_VERTEX_NAME_ATTR,from,agnameof(v));
	}


	/* read edges properties */
	att = agnxtattr(cg,AGEDGE,NULL);
	while(att != NULL)
	{
		/* the only way to iterate over all edges is to iterate
		 * over the vertices */
		for(v = agfstnode(cg); v; v = agnxtnode(cg,v))
		{
			from = find_id(AGID(v),vertices,vsize);
			for(e = agfstout(cg,v); e; e = agnxtout(cg,e))
			{
				to = find_id(AGID(aghead(e)),vertices,vsize);
				igraph_get_eid(g,&eid,from,to,1,0);
				SETEAS(g,att->name,eid,agxget(e,att));
			}
		}
		att = agnxtattr(cg,AGEDGE,att);
	}

	goto cleanup;
error:
	igraph_destroy(g);
cleanup:
	igraph_vector_destroy(&vertices);
error_de:
	igraph_vector_destroy(&edges);
error_d:
	agclose(cg);
	return err;
}
Exemplo n.º 23
0
main(int argc, char *argv[])
{
    Agraph_t **gs;
    Agraph_t **ccs;
    Agraph_t *g;
    Agraph_t *gp;
    char *fname;
    FILE *fp;
    int cnt;
    int i;

    init(argc, argv);
    if (!Files) {
	fprintf(stderr, "No input files given\n");
	exit(1);
    }

    PSinputscale = POINTS_PER_INCH;
    if (doComps) {
	if (verbose)
	    fprintf(stderr, "do Comps\n");
	while (fname = *Files++) {
	    fp = fopen(fname, "r");
	    if (!fp) {
		fprintf(stderr, "Could not open %s\n", fname);
		continue;
	    }
	    g = agread(fp);
	    fclose(fp);
	    if (!g) {
		fprintf(stderr, "Could not read graph\n");
		continue;
	    }
	    printf("%s %d nodes %d edges %sconnected\n",
		   g->name, agnnodes(g), agnedges(g),
		   (isConnected(g) ? "" : "not "));
	    gs = ccomps(g, &cnt, "abc");
	    for (i = 0; i < cnt; i++) {
		gp = gs[i];
		printf(" %s %d nodes %d edges\n", gp->name, agnnodes(gp),
		       agnedges(gp));
	    }
	}
    } else {
	gs = N_GNEW(nFiles, Agraph_t *);
	cnt = 0;
	while (fname = Files[cnt]) {
	    fp = fopen(fname, "r");
	    if (!fp) {
		fprintf(stderr, "Could not open %s\n", fname);
		exit(1);
	    }
	    g = agread(fp);
	    fclose(fp);
	    if (!g) {
		fprintf(stderr, "Could not read graph\n");
		exit(1);
	    }
	    if (!single) {
		graph_init(g);
		ptest_initGraph(g);
	    }
	    initPos(g);
	    /* if (Verbose) dumpG (g); */
	    gs[cnt++] = g;
	}
	if (single) {
	    Agraph_t *root;
	    Agnode_t *n;
	    Agnode_t *np;
	    Agnode_t *tp;
	    Agnode_t *hp;
	    Agedge_t *e;
	    Agedge_t *ep;
	    root = agopen("root", 0);
	    agedgeattr(root, "pos", "");
	    for (i = 0; i < cnt; i++) {
		g = gs[i];
		for (n = agfstnode(g); n; n = agnxtnode(g, n)) {
		    if (agfindnode(root, n->name)) {
			fprintf(stderr,
				"Error: node %s in graph %d (%s) previously added\n",
				n->name, i, Files[i]);
			exit(1);
		    }
		    np = agnode(root, n->name);
		    ND_pos(np)[0] = ND_pos(n)[0];
		    ND_pos(np)[1] = ND_pos(n)[1];
		    ND_coord_i(np).x = ND_coord_i(n).x;
		    ND_coord_i(np).y = ND_coord_i(n).y;
		}
		for (n = agfstnode(g); n; n = agnxtnode(g, n)) {
		    tp = agfindnode(root, n->name);
		    for (e = agfstout(g, n); e; e = agnxtout(g, e)) {
			hp = agfindnode(root, e->head->name);
			ep = agedge(root, tp, hp);
			ED_spl(ep) = ED_spl(e);
		    }
		}
	    }
	    graph_init(root);
	    ptest_initGraph(root);
	    ccs = ccomps(root, &cnt, 0);
	    packGraphs(cnt, ccs, root, margin, doEdges);
	    if (!doEdges)
		copyPos(root);
	    else
		State = GVSPLINES;
	    attach_attrs(root);
	    for (i = 0; i < cnt; i++) {
		agdelete(root, ccs[i]);
	    }
	    agwrite(root, stdout);
	} else {
	    packGraphs(cnt, gs, 0, margin, doEdges);
	    if (doEdges)
		State = GVSPLINES;
	    for (i = 0; i < cnt; i++) {
		if (!doEdges)
		    copyPos(gs[i]);
		attach_attrs(gs[i]);
		agwrite(gs[i], stdout);
	    }
	}
    }
}
Exemplo n.º 24
0
static Agraph_t *gread(FILE * fp)
{
    return agread(fp, (Agdisc_t *) 0);
}
Exemplo n.º 25
0
Arquivo: grafo.c Projeto: gvs11/BCC
//------------------------------------------------------------------------------
grafo le_grafo(FILE *input) {
    int i, j;
    Agnode_t *v;
    Agedge_t *a;
    Agraph_t *g_cgraph;

    // le grafo
    g_cgraph = agread(input, NULL);

    if ( !g_cgraph )
        return NULL;

    // Cria grafo
    grafo g = (grafo) malloc(sizeof(struct grafo));

    // pega tipo do grafo
    g->tipo = agisdirected(g_cgraph);

    g->peso = SEMPESO;

    // pega numero de vertices
    g->n_vertices = agnnodes(g_cgraph);

    // aloca espaco p/ vetor de vertices
    g->vertices = (vertice) malloc( (unsigned int)g->n_vertices * sizeof(struct vertice));

    if (!g->vertices)
        return NULL;

    //Copia nome do grafo
    g->nome = (char *) malloc(strlen(agnameof(g_cgraph))+1);
    strcpy(g->nome, agnameof(g_cgraph));

    g->matriz_dist = NULL;
    //aloca matriz
    g->matriz_adj = (elemento **) malloc((unsigned int)g->n_vertices *  sizeof(elemento *) );

    // zera matriz
    for (i=0; i < g->n_vertices; i++){
        g->matriz_adj[i] = (elemento *) malloc((unsigned int)g->n_vertices * sizeof(elemento) );

        for(j=0; j < g->n_vertices; j++){
            g->matriz_adj[i][j].adjacente = 0;
        }
    }

    i = 0;

    // Copia vertices
    for (v = agfstnode(g_cgraph ); v; v = agnxtnode(g_cgraph ,v), i++) {
        // copia nome
        g->vertices[i].nome = (char *) malloc(strlen(agnameof(v))+1);
        //g->vertice[i].nome = agnameof(v);
        strcpy(g->vertices[i].nome, agnameof(v));

        // seta next vertice
        if (i != agnnodes(g_cgraph) - 1)
            g->vertices[i].next = &g->vertices[i+1];

        //set atribute
        Agnodeinfo_t *p;
        p = (Agnodeinfo_t*) agbindrec(v,"Agnodeinfo_t",sizeof(Agnodeinfo_t),TRUE);
        p->ref_v = i;
    }

    g->vertices[i-1].next = NULL;

    //Copia arestas
    i = 0;
    for (v=agfstnode(g_cgraph); v; v=agnxtnode(g_cgraph,v), i++) {
        if (g->tipo == NAODIRECIONADO){
            for (a=agfstedge(g_cgraph,v); a; a=agnxtedge(g_cgraph,a,v))
                add_aresta(i, v, a, g);

        } else {
            for (a=agfstout(g_cgraph,v); a; a=agnxtout(g_cgraph,a))
                add_aresta(i, v, a, g);
        }
    }

    free(g_cgraph);

    return g;
}
Exemplo n.º 26
0
grafo le_grafo(FILE *input) {

    Agraph_t *ag = agread(input, 0);
    if(!(ag && agisstrict(ag)))
        return NULL;

//	struct grafo *g = malloc(sizeof(struct grafo));
	grafo g = malloc(sizeof(struct grafo));
    if( !g ) return NULL;

	g->vertices = constroi_lista();
    g->nome     = malloc(sizeof(char) * strlen(agnameof(ag)+1));
    strcpy(g->nome, agnameof(ag));
    g->direcionado = agisdirected(ag);
    g->n_vertices  = (unsigned int)agnnodes(ag);
    g->n_arestas   = (unsigned int)agnedges(ag);
    g->ponderado   = 0;

	for( Agnode_t *v = agfstnode(ag); v; v = agnxtnode(ag,v) ){

		vertice vt = malloc(sizeof(struct vertice));
		vt->nome   = malloc(sizeof(char) * strlen(agnameof(v))+1);
		strcpy( vt->nome, agnameof(v) );
		vt->visitado = 0;
		vt->coberto  = 0;
		vt->arestas_saida   = constroi_lista();
		vt->arestas_entrada = constroi_lista();

		insere_lista(vt, g->vertices);
	}

	for( Agnode_t *v = agfstnode(ag); v; v = agnxtnode(ag,v) ){

		vertice vt = busca_vertice(g->vertices, agnameof(v));

		if( g-> direcionado ){
			for( Agedge_t *e = agfstout(ag,v); e; e = agnxtout(ag,e) ){
				aresta at = cria_aresta(g->vertices, e);
				if( at->peso != 0 ) g->ponderado = 1;
				insere_lista(at, vt->arestas_saida);
			}
			for( Agedge_t *e = agfstin(ag,v); e; e = agnxtin(ag,e) ){
				aresta at = cria_aresta(g->vertices, e);
				if( at->peso != 0 ) g->ponderado = 1;
				insere_lista(at, vt->arestas_entrada);
			}
		}
		else {

			for( Agedge_t *e = agfstedge(ag,v); e; e = agnxtedge(ag,e,v) ){
				if( agtail(e) != v ) continue;
				aresta at = cria_aresta(g->vertices, e);
				if( at->peso != 0 ) g->ponderado = 1;
				insere_lista(at, at->origem->arestas_saida);
				insere_lista(at, at->destino->arestas_saida);
			}
		}
	}

	if( agclose(ag) )
		return NULL;
	return g;
}
Exemplo n.º 27
0
bool
GxlFunction::LazyGxlSequence::InternalIterator::next(Item& aItem)
{
  if(!is_open)
  {
    GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "GxlFunction::LazyGxlSequence Iterator consumed without open");
  }
  Item              lItem;
  Agraph_t          *lGraph = 0;
  GVC_t             *lGvc = 0;
  std::fstream       lSVGFile;
  FILE              *lFile = 0;

  if (!arg_iter->next(lItem)) // exhausted
    return false;

  lGvc = gvContext();

  try {

    std::string lTmpFile = theItemSequence->theFunc->getGraphvizTmpFileName(theItemSequence->theFunc->theModule->getItemFactory());
    lSVGFile.open(lTmpFile.c_str(),
        std::fstream::in | std::fstream::out | std::fstream::trunc);

    gxl2dot(theItemSequence->theFunc->theModule->getItemFactory(), lItem, lSVGFile);
    lSVGFile.close();

    lFile = fopen(lTmpFile.c_str(), "r");
    if (!lFile) {
      std::ostringstream lErrorMsg;
      lErrorMsg << "could not read from file " << lTmpFile.c_str();
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", lErrorMsg.str());
    }
#ifdef GRAPHVIZ_USE_CGRAPH
    lGraph = agread(lFile, NULL);
#else
    lGraph = agread(lFile);
#endif    
    fclose(lFile);

    if (!lGraph) {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not read input");
    }

    int blub =  gvLayout(lGvc, lGraph, const_cast<char*>("dot"));
    if ( blub != 0 ) {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not generate layout");
    }

    if ( gvRenderFilename(lGvc, lGraph, const_cast<char*>("svg"),
                          const_cast<char*>(lTmpFile.c_str())) != 0 )  {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not render graph");
    }

    lSVGFile.open(lTmpFile.c_str(), std::ifstream::in);
    if (lSVGFile.bad()) {
      std::ostringstream lErrorMsg;
      lErrorMsg << "could not read from file " << lTmpFile.c_str();
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", lErrorMsg.str());
    }

    aItem = Zorba::getInstance(0)->getXmlDataManager()->parseXML(lSVGFile);

    gvFreeLayout(lGvc, lGraph);
    agclose(lGraph);
    gvFreeContext(lGvc);

    remove(lTmpFile.c_str());
  } catch (...) {
    if (lGraph) {
      gvFreeLayout(lGvc, lGraph);
      agclose(lGraph);
    }
    gvFreeContext(lGvc);
    throw;
  }

  return true;

} /* GxlFunction::LazyGxlSequence::next */