Beispiel #1
0
/**
 * @brief Reads the database into memory.
 *
 * @details Reads the database into memory so we can speedup computation.
 *
 * @param filenames   Name of input files.
 * @param nproteins   Number of proteins (number of input files).
 * @param nfeatures   Number of features for all proteins.
 * @param naminoacids Largest number of amino acids for all proteins.
 *
 * @returns The database.
 * 
 * @todo Check for bad file format.
 */
void database_read
(const char **filenames, unsigned nproteins, unsigned nfeatures)
{
	unsigned width;
	
	/* Sanity check. */
	assert(filenames != NULL);
	assert(nproteins != 0);
	assert(nfeatures != 0);

	/* Allocate database. */
	database.nproteins = nproteins;
	database.labels = smalloc(nproteins*sizeof(unsigned));
	database.data = smalloc(nfeatures*sizeof(double *));
	width = database.maxaminoacids*nproteins;
	for (unsigned i = 0; i < nfeatures; i++)
		database.data[i] = smalloc(width*sizeof(double));

	/* Read database. */
	for (unsigned wprotein = 0; wprotein < nproteins; wprotein++)
	{
		char *line;          /* Working line.        */
		unsigned waminoacid; /* Current amino acid. */
		FILE *wfile;         /* Working file.        */

		/* Open working file. */
		wfile = fopen(filenames[wprotein], "r");
		if (wfile == NULL)
			error ("cannot open input file");
		
		/* Read label. */
		line = readline(wfile);
		sscanf(line, "%u", &database.labels[wprotein]);
		free(line);
		
		/* Read amino acid. */
		waminoacid = 0;
		while (!feof(wfile))
		{
			char *token;       /* Working token.                  */
			unsigned wfeature; /* Working feature.                */
			unsigned j;        /* waminoacid*nproteins + wprotein */
			
			line = readline(wfile);
			
			/* Read line. */
			wfeature = 0;
			token = strtok(line, ";");
			j = waminoacid*nproteins + wprotein;
			while (token != NULL)
			{
				sscanf(token, "%lf", &database.data[wfeature][j]);
				
				token = strtok(NULL, ";");
				wfeature++;
				
				if (wfeature > nfeatures)
					error("bad input file");
				if (waminoacid > database.maxaminoacids)
					error("bad input file");
			}
			
			waminoacid++;
			free(line);
		}
		
		fclose(wfile);
	}
	
	database_transpose();
}
Beispiel #2
0
Datei: main.c Projekt: goma/goma
int
main(int argc, char **argv)
     
     /*
      * Initial main driver for GOMA. Derived from a (1/93) release of
      * the rf_salsa program by
      *        
      *        Original Authors: John  Shadid (1421)
      *		                 Scott Hutchinson (1421)
      *        		         Harry Moffat (1421)
      *       
      *        Date:		12/3/92
      * 
      *
      *        Updates and Changes by:
      *                           Randy Schunk (9111)
      *                           P. A. Sackinger (9111)
      *                           R. R. Rao       (9111)
      *                           R. A. Cairncross (Univ. of Delaware)
      *        Dates:           2/93 - 6/96
      *
      *       Modified for continuation
      *                           Ian Gates
      *       Dates:            2/98 - 10/98
      *       Dates:            7/99 - 8/99
      * 
      * Last modified: Wed  June 26 14:21:35 MST 1994 [email protected]
      * Hello.
      * 
      * Note: Many modifications from an early 2/93 pre-release
      *	      version of rf_salsa were made by various persons 
      *       in order to test ideas about moving/deforming meshes...
      */ 
{
  /* Local Declarations */

  double time_start, total_time;   /* timing variables */
#ifndef PARALLEL
  /*  struct tm *tm_ptr;               additional serial timing variables */
  time_t now;
#endif

  int error;
  int i;
  int j;

  char	**ptmp;
  char *yo;

  struct Command_line_command **clc=NULL; /* point to command line structure */
  int           nclc = 0;		/* number of command line commands */

/********************** BEGIN EXECUTION ***************************************/

#ifdef FP_EXCEPT
  feenableexcept ((FE_OVERFLOW | FE_DIVBYZERO | FE_INVALID));
#endif

/* assume number of commands is less than or equal to the number of 
 * arguments in the command line minus 1 (1st is program name) */

  /*
  *  Get the name of the executable, yo
  */
  yo = argv[0];

#ifdef PARALLEL
  MPI_Init(&argc, &argv);
  time_start = MPI_Wtime();
#endif /* PARALLEL */
#ifndef PARALLEL
  (void)time(&now);
  time_start = (double)now;
#endif /* PARALLEL */

  time_goma_started = time_start;

  Argv = argv;

  Argc = argc;

#ifdef PARALLEL
  /*
   * Determine the parallel processing status, if any. We need to know
   * pretty early if we're "one of many" or the only process.
   */

  error = MPI_Comm_size(MPI_COMM_WORLD, &Num_Proc);
  error = MPI_Comm_rank(MPI_COMM_WORLD, &ProcID);

  /*
   * Setup a default Proc_config so we can use utility routines 
   * from Aztec
   */

  AZ_set_proc_config(Proc_Config, MPI_COMM_WORLD);

  /* set the output limit flag if need be */

  if( Num_Proc > DP_PROC_PRINT_LIMIT ) Unlimited_Output = FALSE;

#ifdef HAVE_MPE_H
  error = MPE_Init_log();
#endif /* HAVE_MPE_H */

  Dim = 0;			/* for any hypercube legacy code...  */

#endif /* PARALLEL */
  
#ifndef PARALLEL
  Dim        = 0;
  ProcID     = 0;
  Num_Proc   = 1;
#endif /* PARALLEL */


  /*
  *   HKM - Change the ieee exception handling based on the machine and
  *         the level of debugging/speed desired. This call currently causes
  *         core dumps for floating point exceptions.
  */

  handle_ieee();
  
  log_msg("--------------");
  log_msg("GOMA begins...");

  /*
   * Some initial stuff that only the master process does.
   */

  if ( ProcID == 0 )
    {
      if (argc > 1)
	{
	  log_msg("Preprocessing command line options.");
	  clc = (struct Command_line_command **) 
	    smalloc( argc * sizeof(struct Command_line_command *));
	  for (i=0; i<argc; i++)
	    {
	      clc[i] = (struct Command_line_command *) 
		smalloc(sizeof(struct Command_line_command));
	      clc[i]->type   = 0; /* initialize command line structure */
	      clc[i]->i_val  = 0;
	      clc[i]->r_val  = 0.;
	      clc[i]->string = (char *) 
		smalloc(MAX_COMMAND_LINE_LENGTH*sizeof(char));
	      for ( j=0; j<MAX_COMMAND_LINE_LENGTH; j++)
		{
		  clc[i]->string[j] = '\0';
		}
#ifdef DEBUG
	      fprintf(stderr, "clc[%d]->string is at 0x%x\n", i, clc[i]->string);
	      fprintf(stderr, "clc[%d]         is at 0x%x\n", i, clc[i]);
#endif
	    }
	}

      strcpy(Input_File, "input");
      strcpy(Echo_Input_File , "echo_input");

      if (argc > 1) translate_command_line(argc, argv, clc, &nclc);
	  	  
	  ECHO("OPEN", Echo_Input_File);
      
	  echo_command_line( argc, argv, Echo_Input_File );
      print_code_version();
      ptmp = legal_notice;
      while ( strcmp(*ptmp, LAST_LEGAL_STRING) != 0 )
	{
	  fprintf(stderr, "%s", *ptmp++);
	}
    }

  /*
   *  Allocate the uniform problem description structure and
   *  the problem description structures on all processors
   */
  error = pd_alloc();
  EH(error, "pd_alloc problem");

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier after pd_alloc\n", ProcID);
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif

  log_msg("Allocating mp, gn, ...");

  error = mp_alloc();
  EH(error, "mp_alloc problem");

  error = gn_alloc();
  EH(error, "gn_alloc problem");

  error = ve_alloc();
  EH(error, "ve_alloc problem");

  error = elc_alloc();
  EH(error, "elc_alloc problem");

  error = elc_rs_alloc();
  EH(error, "elc_alloc problem");

  error = cr_alloc();
  EH(error, "cr_alloc problem");

  error = evp_alloc();
  EH(error, "evp_alloc problem");

  error = tran_alloc();
  EH(error, "tran_alloc problem");

  error = eigen_alloc();
  EH(error, "eigen_alloc problem");

  error = cont_alloc();
  EH(error, "cont_alloc problem");

  error = loca_alloc();
  EH(error, "loca_alloc problem");

  error = efv_alloc();
  EH(error, "efv_alloc problem");

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before read_input_file()\n", ProcID);
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif

  /*
   * Read ASCII input file, data files, related exodusII FEM databases.
   */	
  if ( ProcID == 0 )
    {
      log_msg("Reading input file ...");
      read_input_file(clc, nclc); /* Read ascii input file get file names */

      /* update inputed data to account for command line arguments that
       * might override the input deck...
       */
      log_msg("Overriding any input file specs w/ any command line specs...");
      if (argc > 1) apply_command_line(clc, nclc);

#ifdef DEBUG
      DPRINTF(stderr, "apply_command_line() is done.\n");
#endif
    }

  /*
   * The user-defined material properties, etc. available to goma users
   * mean that some dynamically allocated data needs to be communicated.
   *
   * To handle this, sizing information from the input file scan is
   * broadcast in stages so that the other processors can allocate space
   * accordingly to hold the data.
   *
   * Note: instead of handpacking a data structure, use MPI derived datatypes
   * to gather and scatter. Pray this is done efficiently. Certainly it costs
   * less from a memory standpoint.
   */

#ifdef PARALLEL

  /*
   *  Make sure the input file was successully processed before moving on
   */
  check_parallel_error("Input file error");


  /*
   * This is some sizing information that helps fit a little bit more
   * onto the ark later on.
   */

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before noahs_raven()\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif

  noahs_raven();

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before MPI_Bcast of Noahs_Raven\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif

  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Raven->new_type, 0, MPI_COMM_WORLD);

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier after Bcast/before raven_landing()\n", 
	  ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif  
  /*
   * Get the other processors ready to handle ark data.
   */

  raven_landing();

#ifdef DEBUG
  fprintf(stderr, "P_%d at barrier before noahs_ark()\n", ProcID);
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
  
  
  /*
   * This is the main body of communicated information, including some
   * whose sizes were determined because of advanced legwork by the raven.
   */

  noahs_ark();
  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Ark->new_type, 0, MPI_COMM_WORLD);

  /*
   * Chemkin was initialized on processor zero during the input file
   * process. Now, distribute it to all processors
   */
#ifdef USE_CHEMKIN
  if (Chemkin_Needed) {
    chemkin_initialize_mp();
  }
#endif 

  /*
   * Once the ark has landed, there are additional things that will need to
   * be sent by dove. Example: BC_Types[]->u-BC arrays.
   *
   */

  ark_landing();

  noahs_dove();
  MPI_Bcast(MPI_BOTTOM, 1, Noahs_Dove->new_type, 0, MPI_COMM_WORLD);


#endif          /* End of ifdef PARALLEL */


  /*
   * We sent the packed line to all processors that contained geometry
   * creation commands.  Now we need to step through it and create
   * geometry as we go (including possibly reading an ACIS .sat file).
   *
   */

  /* Check to see if BRK File option exists and if so check if file exits */
  if (Brk_Flag == 1) {
    check_for_brkfile(Brk_File);
  }
  check_parallel_error("Error encountered in check for brkfile");

  /* Now break the exodus files */
  if (Num_Proc > 1 && ProcID == 0 && Brk_Flag == 1) {
    call_brk();
  }
  check_parallel_error("Error in brking exodus files");
  MPI_Barrier(MPI_COMM_WORLD);

  /*
   * For parallel execution, assume the following variables will be changed
   * to reflect the multiple file aspect of the problem.
   *
   *	FEM file = file.exoII		--> file_3of15.exoII
   *
   *	Output EXODUS II file = out.exoII --> out_3of15.exoII
   *
   */


  /*
   * Allocate space for structures holding the EXODUS II finite element
   * database information and for the Distributed Processing information.
   *
   * These are mostly skeletons with pointers that get allocated in the
   * rd_exoII and rd_dpi routines. Remember to free up those arrays first
   * before freeing the major pointers.
   */

  EXO_ptr = alloc_struct_1(Exo_DB, 1);
  init_exo_struct(EXO_ptr);
  DPI_ptr = alloc_struct_1(Dpi, 1);
  init_dpi_struct(DPI_ptr);  

  log_msg("Reading mesh from EXODUS II file...");
  error = read_mesh_exoII(EXO_ptr, DPI_ptr);

  /*
   *   Missing files on any processor are detected at a lower level
   *   forcing a return to the higher level
   *         rd_exo -->  rd_mesh  -->  main
   *   Shutdown now, if any of the exodus files weren't found
   */
  if (error < 0) {
#ifdef PARALLEL
    MPI_Finalize();
#endif
    return(-1);
  }

  /*
   * All of the MPI_Type_commit() calls called behind the scenes that build
   * the dove, ark and raven really allocated memory. Let's free it up now that
   * the initial information has been communicated.
   */

#ifdef PARALLEL
  MPI_Type_free(&(Noahs_Raven->new_type));
  MPI_Type_free(&(Noahs_Ark->new_type));
  MPI_Type_free(&(Noahs_Dove->new_type));
#endif   

  /*
   * Setup the rest of the Problem Description structure that depends on
   * the mesh that was read in from the EXODUS II file...
   * 
   * Note that memory allocation and some setup has already been performed
   * in mm_input()...
   */

  error = setup_pd();
  EH( error, "Problem setting up Problem_Description.");
  /*
   * Let's check to see if we need the large elasto-plastic global tensors
   * and allocate them if so 
   */
  error = evp_tensor_alloc(EXO_ptr);
  EH( error, "Problems setting up evp tensors");
  
  /*
   * Now that we know about what kind of problem we're solving and the
   * mesh information, let's allocate space for elemental assembly structures
   *
   */
#ifdef DEBUG
  DPRINTF(stderr, "About to assembly_alloc()...\n");
#endif
  log_msg("Assembly allocation...");

  error = assembly_alloc(EXO_ptr);
  EH( error, "Problem from assembly_alloc");

  if (Debug_Flag)  {
    DPRINTF(stderr, "%s:  setting up EXODUS II output files...\n", yo);
  }

  /*
   * These are not critical - just niceties. Also, they should not overburden
   * your db with too much of this - they're capped verbiage compliant routines.
   */

  add_qa_stamp(EXO_ptr);

  add_info_stamp(EXO_ptr);

#ifdef DEBUG
  fprintf(stderr, "added qa and info stamps\n");
#endif

  /*
   * If the output EXODUS II database file is different from the input
   * file, then we'll need to replicate all the basic mesh information.
   * But, remember that if we're parallel, that the output file names must
   * be multiplexed first...
   */
  if ( Num_Proc > 1 )
    {
      multiname(ExoFileOut,     ProcID, Num_Proc);      
      multiname(Init_GuessFile, ProcID, Num_Proc);

      if ( strcmp( Soln_OutFile, "" ) != 0 )
	{
	  multiname(Soln_OutFile, ProcID, Num_Proc);
	}

      if( strcmp( ExoAuxFile, "" ) != 0 )
        {
          multiname(ExoAuxFile, ProcID, Num_Proc);
        }

      if( efv->Num_external_field != 0 )
        {
          for( i=0; i<efv->Num_external_field; i++ )
            {
              multiname(efv->file_nm[i], ProcID, Num_Proc);
            }
        }
    }


  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *   Preprocess the exodus mesh
   *        -> Allocate pointers to structures containing element
   *           side bc info, First_Elem_Side_BC_Array, and
   *           element edge info, First_Elem_Edge_BC_Array.
   *        -> Determine Unique_Element_Types[] array
   */
#ifdef DEBUG
  fprintf(stderr, "pre_process()...\n");
#endif
  log_msg("Pre processing of mesh...");
#ifdef PARALLEL
  error = MPI_Barrier(MPI_COMM_WORLD);
#endif
  pre_process(EXO_ptr);

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   * Load up a few key indeces in the bfd prototype basis function structures
   * and make sure that each active eqn/vbl has a bf[v] that points to the
   * right bfd[]...needs pre_process to find out the number of unique
   * element types in the problem.
   */

#ifdef DEBUG
  fprintf(stderr, "bf_init()...\n");
#endif
  log_msg("Basis function initialization...");
  error = bf_init(EXO_ptr);
  EH( error, "Problem from bf_init");

  /*
   * check for parallel errors before continuing
   */
  check_parallel_error("Error encountered in problem setup");

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/  
  /*
   * Allocate space for each communication exchange description.
   */
#ifdef PARALLEL
#ifdef DEBUG
  fprintf(stderr, "P_%d: Parallel cx allocation\n", ProcID);
#endif
  if (DPI_ptr->num_neighbors > 0) {
    cx = alloc_struct_1(Comm_Ex, DPI_ptr->num_neighbors);
    Request = alloc_struct_1(MPI_Request, 
			     Num_Requests * DPI_ptr->num_neighbors);
    Status = alloc_struct_1(MPI_Status, 
			    Num_Requests * DPI_ptr->num_neighbors);
  }
#endif

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *                           SET UP THE PROBLEM
   *
   * Setup node-based structures
   * Finalise how boundary conditions are to be handled
   * Determine what unknowns are at each owned node and then tell
   *  neighboring processors about your nodes
   * Set up communications pattern for fast unknown updates between
   *  processors.
   */
  (void) setup_problem(EXO_ptr, DPI_ptr);

  /*
   * check for parallel errors before continuing
   */
  check_parallel_error("Error encountered in problem setup");

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *               CREATE BRK_FILE IF ONE DOES NOT EXIST
   *
   * If no Brk_File exists but the option was configured in the input or
   * optional command we create one now and exit from goma.
   */
  if ( Brk_Flag == 2 ) {
    write_brk_file(Brk_File, EXO_ptr);
    exit(0);
  }
  
  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *                     WRITE OUT INITIAL INFO TO EXODUS FILE
   */

  /*
   *  Only have to initialize the exodus file if we are using different
   *  files for the output versus the input mesh
   */
  if (strcmp(ExoFile, ExoFileOut)) {
    /*
     * Temporarily we'll need to renumber the nodes and elements in the
     * mesh to be 1-based. After writing, return to the 0 based indexing
     * that is more convenient in C.
     */
#ifdef DEBUG
    fprintf(stderr, "1-base; wr_mesh; 0-base\n");
#endif
    one_base(EXO_ptr);
    wr_mesh_exo(EXO_ptr, ExoFileOut, 0);
    zero_base(EXO_ptr);

    /*
     * If running on a distributed computer, augment the plain finite
     * element information of EXODUS with the description of how this
     * piece fits into the global problem.
     */
    if (Num_Proc > 1) {
#ifdef PARALLEL
#ifdef DEBUG
      fprintf(stderr, "P_%d at barrier before wr_dpi()\n", ProcID);
      fprintf(stderr, "P_%d ExoFileOut = \"%s\"\n", ProcID, ExoFileOut);
      error = MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif
      wr_dpi(DPI_ptr, ExoFileOut, 0);
    }
  }

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *                           SOLVE THE PROBLEM
   */

  if (Debug_Flag) {
    switch (Continuation) {
    case ALC_ZEROTH:
        P0PRINTF("%s: continue_problem (zeroth order) ...\n", yo);
        break;
    case  ALC_FIRST:
        P0PRINTF("%s: continue_problem (first order) ...\n", yo);
        break;
    case HUN_ZEROTH:
        P0PRINTF("%s: hunt_problem (zeroth order) ...\n", yo);
        break;
    case  HUN_FIRST:
        P0PRINTF("%s: hunt_problem (first order) ...\n", yo);
        break;
    case LOCA:
        P0PRINTF("%s: do_loca ...\n", yo);
        break;
    default:
        P0PRINTF("%s: solve_problem...\n", yo);
        break;
    }
  }  
#ifdef DEBUG
  switch (Continuation) {
  case ALC_ZEROTH:
      DPRINTF(stderr, "%s: continue_problem (zeroth order) ...\n", yo);
      break;
  case  ALC_FIRST:
      DPRINTF(stderr, "%s: continue_problem (first order) ...\n", yo);
      break;
  case HUN_ZEROTH:
      DPRINTF(stderr, "%s: hunt_problem (zeroth order) ...\n", yo);
      break;
  case  HUN_FIRST:
      DPRINTF(stderr, "%s: hunt_problem (first order) ...\n", yo);
      break;
  case LOCA:
      DPRINTF(stderr, "%s: do_loca ...\n", yo);
      break;
  default:
      DPRINTF(stderr, "%s: solve_problem...\n", yo);
      break;
  }
#endif

    
  if( TimeIntegration == TRANSIENT)
        {
        Continuation = ALC_NONE;
        if (Debug_Flag) {
          P0PRINTF("%s: solve_problem...TRANSIENT superceded Continuation...\n", yo);
          }
#ifdef DEBUG
   DPRINTF(stderr, "%s: solve_problem...TRANSIENT superceded Continuation...\n", yo);
#endif
        solve_problem(EXO_ptr, DPI_ptr, NULL);
        }  

  switch (Continuation) {
  case ALC_ZEROTH:
  case ALC_FIRST:
    log_msg("Solving continuation problem");
    continue_problem(cx, EXO_ptr, DPI_ptr);
    break;
  case HUN_ZEROTH:
  case HUN_FIRST:
    log_msg("Solving hunt problem");
    hunt_problem(cx, EXO_ptr, DPI_ptr);
    break;
  case LOCA:
    log_msg("Solving continuation problem with LOCA");
    error = do_loca(cx, EXO_ptr, DPI_ptr);
    break;
  default:
    log_msg("Solving problem");
    if (loca_in->Cont_Alg == LOCA_LSA_ONLY)
      {
        error = do_loca(cx, EXO_ptr, DPI_ptr);
      }
    else if(TimeIntegration != TRANSIENT)
      {
        solve_problem(EXO_ptr, DPI_ptr, NULL);
      }
    break;
  }

#ifdef PARALLEL
   MPI_Barrier(MPI_COMM_WORLD);
#endif

  if (ProcID == 0 && Brk_Flag == 1 && Num_Proc > 1) {
    fix_output();
  }
  
  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *  PRINT A MESSAGE TO STDOUT SAYING WE ARE DONE
   */
  P0PRINTF("\n-done\n\n");

  /***********************************************************************/
  /***********************************************************************/
  /***********************************************************************/
  /*
   *       FREE MEMORY ALLOCATED BY THE PROGRAM
   */
  /*
   * free the element block / element based structures
   */
  free_element_blocks(EXO_ptr);

  /*
   * free nodal based structures
   */
  free_nodes();
#ifdef FREE_PROBLEM
  free_problem ( EXO_ptr, DPI_ptr );
#endif

  /*
   * Free command line stuff
   */
  if ( ProcID == 0 )
    {
      if ( argc > 1 ) 
	{
	  for (i=0; i<argc; i++)
	    {
#ifdef DEBUG
	      fprintf(stderr, "clc[%d]->string &= 0x%x\n", i, clc[i]->string);
	      fprintf(stderr, "clc[%d]         &= 0x%x\n", i, clc[i]);
#endif
	      safer_free((void **) &(clc[i]->string));
	      safer_free((void **) (clc + i));
	    }
	  safer_free((void **) &clc);
	}
    }

  /*
   * Free exodus database structures
   */
  free_exo(EXO_ptr);
  safer_free((void **) &EXO_ptr);

  if ( Num_Proc > 1 )
  {
    free_dpi(DPI_ptr);
  }
  else
  {
    free_dpi_uni(DPI_ptr);
  }

  safer_free((void **) &DPI_ptr);

  /*
   * Remove front scratch file [/tmp/lu.'pid'.0]
   */
  if (Linear_Solver == FRONT) 	
    {
  unlerr = unlink(front_scratch_directory);
  WH(unlerr, "Unlink problem with front scratch file");
    }


#ifdef PARALLEL
  total_time = ( MPI_Wtime() - time_start )/ 60. ;
  DPRINTF(stderr, "\nProc 0 runtime: %10.2f Minutes.\n\n",total_time);
  MPI_Finalize();
#endif  
#ifndef PARALLEL
  (void)time(&now);
  total_time = (double)(now) - time_start;
  fprintf(stderr, "\nProc 0 runtime: %10.2f Minutes.\n\n",total_time/60);
#endif  
  fflush(stdout);
  fflush(stderr);
  log_msg("GOMA ends normally.");
  return (0);
}
Beispiel #3
0
void gen_citations(paragraph * source, keywordlist * kl)
{
  paragraph *para;
  int bibnum = 0;

  for (para = source; para; para = para->next)
  {
    word *ptr;

    /*
     * \BR and \nocite paragraphs get special processing here.
     */
    if (para->type == para_BR)
    {
      keyword *kw = kw_lookup(kl, para->keyword);
      if (!kw)
      {
        error(err_nosuchkw, &para->fpos, para->keyword);
      } else if (kw->text)
      {
        error(err_multiBR, &para->fpos, para->keyword);
      } else
      {
        kw->text = dup_word_list(para->words);
      }
    } else if (para->type == para_NoCite)
    {
      wchar_t *wp = para->keyword;
      while (*wp)
      {
        cite_biblio(kl, wp, para->fpos);
        wp = uadv(wp);
      }
    }

    /*
     * Scan for keyword references.
     */
    for (ptr = para->words; ptr; ptr = ptr->next)
    {
      if (ptr->type == word_UpperXref || ptr->type == word_LowerXref
          || ptr->type == word_FreeTextXref)
        cite_biblio(kl, ptr->text, ptr->fpos);
    }
  }

  /*
   * We're now almost done; all that remains is to scan through
   * the cited bibliography entries and invent default citation
   * texts for the ones that don't already have explicitly
   * provided \BR text.
   */
  for (para = source; para; para = para->next)
  {
    if (para->type == para_BiblioCited)
    {
      keyword *kw = kw_lookup(kl, para->keyword);
      assert(kw != NULL);
      if (!kw->text)
      {
        word *wd = smalloc(sizeof(word));
        wd->text = gentext(++bibnum);
        wd->type = word_Normal;
        wd->alt = NULL;
        wd->next = NULL;
        kw->text = wd;
      }
      para->kwtext = kw->text;
    }
  }
}
Beispiel #4
0
/*
 * Rewrite the results of a directory read to reflect current 
 * name space bindings and mounts.  Specifically, replace
 * directory entries for bind and mount points with the results
 * of statting what is mounted there.  Except leave the old names.
 */
static long
mountfix(Chan *c, uchar *op, long n, long maxn)
{
	char *name;
	int nbuf, nname;
	Chan *nc;
	Mhead *mh;
	Mount *m;
	uchar *p;
	int dirlen, rest;
	long l;
	uchar *buf, *e;
	Dir d;

	p = op;
	buf = nil;
	nbuf = 0;
	for(e=&p[n]; p+BIT16SZ<e; p+=dirlen){
		dirlen = dirfixed(p, e, &d);
		if(dirlen < 0)
			break;
		nc = nil;
		mh = nil;
		if(findmount(&nc, &mh, d.type, d.dev, d.qid)){
			/*
			 * If it's a union directory and the original is
			 * in the union, don't rewrite anything.
			 */
			for(m=mh->mount; m; m=m->next)
				if(eqchantdqid(m->to, d.type, d.dev, d.qid, 1))
					goto Norewrite;

			name = dirname(p, &nname);
			/*
			 * Do the stat but fix the name.  If it fails, leave old entry.
			 * BUG: If it fails because there isn't room for the entry,
			 * what can we do?  Nothing, really.  Might as well skip it.
			 */
			if(buf == nil){
				buf = smalloc(4096);
				nbuf = 4096;
			}
			if(waserror())
				goto Norewrite;
			l = devtab[nc->type]->stat(nc, buf, nbuf);
			l = dirsetname(name, nname, buf, l, nbuf);
			if(l == BIT16SZ)
				error("dirsetname");
			poperror();

			/*
			 * Shift data in buffer to accomodate new entry,
			 * possibly overflowing into rock.
			 */
			rest = e - (p+dirlen);
			if(l > dirlen){
				while(p+l+rest > op+maxn){
					mountrock(c, p, &e);
					if(e == p){
						dirlen = 0;
						goto Norewrite;
					}
					rest = e - (p+dirlen);
				}
			}
			if(l != dirlen){
				memmove(p+l, p+dirlen, rest);
				dirlen = l;
				e = p+dirlen+rest;
			}

			/*
			 * Rewrite directory entry.
			 */
			memmove(p, buf, l);

		    Norewrite:
			cclose(nc);
			putmhead(mh);
		}
	}
	if(buf)
		free(buf);

	if(p != e)
		error("oops in rockfix");

	return e-op;
}
Beispiel #5
0
/* ----------------------------------------------------------------------
 * Command line reading and parsing.
 */
struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
{
    char *line;
    int linelen, linesize;
    struct sftp_command *cmd;
    char *p, *q, *r;
    int quoting;

    if ((mode == 0) || (modeflags & 1)) {
	printf("psftp> ");
    }
    fflush(stdout);

    cmd = smalloc(sizeof(struct sftp_command));
    cmd->words = NULL;
    cmd->nwords = 0;
    cmd->wordssize = 0;

    line = NULL;
    linesize = linelen = 0;
    while (1) {
	int len;
	char *ret;

	linesize += 512;
	line = srealloc(line, linesize);
	ret = fgets(line + linelen, linesize - linelen, fp);

	if (!ret || (linelen == 0 && line[0] == '\0')) {
	    cmd->obey = sftp_cmd_quit;
	    if ((mode == 0) || (modeflags & 1))
		printf("quit\n");
	    return cmd;		       /* eof */
	}
	len = linelen + strlen(line + linelen);
	linelen += len;
	if (line[linelen - 1] == '\n') {
	    linelen--;
	    line[linelen] = '\0';
	    break;
	}
    }
    if (modeflags & 1) {
	printf("%s\n", line);
    }

    p = line;
    while (*p && (*p == ' ' || *p == '\t'))
	p++;

    if (*p == '!') {
	/*
	 * Special case: the ! command. This is always parsed as
	 * exactly two words: one containing the !, and the second
	 * containing everything else on the line.
	 */
	cmd->nwords = cmd->wordssize = 2;
	cmd->words = srealloc(cmd->words, cmd->wordssize * sizeof(char *));
	cmd->words[0] = "!";
	cmd->words[1] = p+1;
    } else {

	/*
	 * Parse the command line into words. The syntax is:
	 *  - double quotes are removed, but cause spaces within to be
	 *    treated as non-separating.
	 *  - a double-doublequote pair is a literal double quote, inside
	 *    _or_ outside quotes. Like this:
	 *
	 *      firstword "second word" "this has ""quotes"" in" and""this""
	 *
	 * becomes
	 *
	 *      >firstword<
	 *      >second word<
	 *      >this has "quotes" in<
	 *      >and"this"<
	 */
	while (*p) {
	    /* skip whitespace */
	    while (*p && (*p == ' ' || *p == '\t'))
		p++;
	    /* mark start of word */
	    q = r = p;		       /* q sits at start, r writes word */
	    quoting = 0;
	    while (*p) {
		if (!quoting && (*p == ' ' || *p == '\t'))
		    break;		       /* reached end of word */
		else if (*p == '"' && p[1] == '"')
		    p += 2, *r++ = '"';    /* a literal quote */
		else if (*p == '"')
		    p++, quoting = !quoting;
		else
		    *r++ = *p++;
	    }
	    if (*p)
		p++;		       /* skip over the whitespace */
	    *r = '\0';
	    if (cmd->nwords >= cmd->wordssize) {
		cmd->wordssize = cmd->nwords + 16;
		cmd->words =
		    srealloc(cmd->words, cmd->wordssize * sizeof(char *));
	    }
	    cmd->words[cmd->nwords++] = q;
	}
    }

    /*
     * Now parse the first word and assign a function.
     */

    if (cmd->nwords == 0)
	cmd->obey = sftp_cmd_null;
    else {
	const struct sftp_cmd_lookup *lookup;
	lookup = lookup_command(cmd->words[0]);
	if (!lookup)
	    cmd->obey = sftp_cmd_unknown;
	else
	    cmd->obey = lookup->obey;
    }

    return cmd;
}
Beispiel #6
0
/* this function loads clusters from file produced by PROCLU */
int LoadClustersFromFile(char *filename, RLINK *cstart)
{
    int i, sourcesetid, cluserid, direction = -1, clustersread = 0, pos, neg;
    RD *a;
    int repeatkey, repeatcount;
    FILE *fp;
    void *vptr;
    char symbol, clustername[100], comment[510], pattern[2010] = "";
    int  maxsize, minsize, representative;
    EASY_LIST *elist;
    EASY_NODE *nof1;
    RLINK *citem = NULL;

    /* open cluster file for reading */
    fp = fopen(filename, "r");

    if (fp == NULL) {
        printf("\n\nUnable to open intermediate cluster file!");
        exit(1);
        return 0;
    }


    /* loop for every cluster */
    while (1) {
        /* read the next symbol (ignore white space) */
        i = fscanf(fp, " %c", &symbol);

        if (i != 1) break;

        if (symbol != '@') {
            printf("Invalid format detected in cluster file 1!");
            exit(1);
        }

        /* increase cluster count */
        clustercount++;
        clustersread++;

        if (NULL != cstart && clustercount > totclusters) {
            printf("\n\nError: Too many clusters? clustercount=%d totclusters=%d\n\n", clustercount, totclusters);
            exit(1);

        }

        if (NULL != cstart) {
            citem = cstart + clustercount - 1;
            citem->cid = clustercount;

            /* create temp list */
            elist = EasyListCreate(NULL, free);
        }


        /* loop for every member */
        representative = 0;
        repeatcount = 0;

        while (1) {
            /* read number */
            i = fscanf(fp, "%d", &repeatkey);

            if (i != 1) {
                printf("Invalid format detected in cluster file 2!");
                exit(1);
            }

            repeatcount++;

            if (repeatcount == 1) representative = repeatkey;

            /* read symbol */
            i = fscanf(fp, " %c", &symbol);

            if (i != 1 || (symbol != '\'' && symbol != '"')) {
                printf("\n\nUnexpected value qualifier detected in cluster file!");
                exit(1);
            }

            /* assign direction */
            if (symbol == '\'')
                direction = 0;
            else
                direction = 1;


            /* do something with it */
            //printf(" %d%c",repeatkey,symbol);
            if (NULL != cstart) { EasyListInsertHead(elist, RDCreate(repeatkey, direction)); }

            /* read a character */
            symbol = 0;
            i = fscanf(fp, " %c", &symbol);


            /* if no more characters then break */
            if (i != 1) break;

            /* if comment, read it and  then break */
            if (symbol == '#')  {
                fscanf(fp, "%s", comment);
                //fscanf(fp," %c",&symbol); // scan extra character
                break;
            }

            /* put character back */
            ungetc(symbol, fp);

            /* if character was a digit continue otherwise break */
            if ((symbol >= '0' && symbol <= '9') || symbol == '-') continue;
            else break;
        }

        //printf("\n");
        if (NULL != citem) {

            /* count pos and neg */
            pos = 0; neg = 0;

            for (nof1 = elist->head; nof1 != NULL; nof1 = nof1->next) {
                a = (RD *)EasyListItem(nof1);

                if (a->id >= 0) pos++; else neg++;
            }


            TotalReads += pos;
            TotalRefs += neg;

            citem->idlist = smalloc(pos * sizeof(int));
            citem->dirlist = smalloc(pos * sizeof(char));
            citem->negidlist = smalloc(neg * sizeof(int));
            citem->negdirlist = smalloc(neg * sizeof(char));
            citem->next = NULL;


            /* insert into RLINK structure and free temp list */
            pos = 0; neg = 0;

            for (nof1 = elist->head; nof1 != NULL; nof1 = nof1->next) {
                a = (RD *)EasyListItem(nof1);

                if (a->id >= 0) {
                    citem->idlist[pos] = a->id;
                    citem->dirlist[pos] = a->dir;
                    pos++;
                }
                else {
                    citem->negidlist[neg] = a->id;
                    citem->negdirlist[neg] = a->dir;
                    neg++;
                }
            }

            citem->refs = neg;
            citem->reads = pos;
            EasyListDestroy(elist);

        }

    }

    /* close file */
    fclose(fp);


    return clustersread;
}
Beispiel #7
0
static const char *
cygterm_init(void *frontend_handle, void **backend_handle,
             Config *cfg,
             char *unused_host, int unused_port,
             char **realhost, int nodelay, int keepalive)
{
	/* XXX: I'm not sure if it is OK to overload Plug like this.
	 * cygterm_accepting should only be used for the listening socket
	 * (local->a) while the cygterm_closing, cygterm_receive, and cygterm_sent
	 * should be used only for the actual connection (local->s).
	 */
	static const struct plug_function_table fn_table = {
		cygterm_log,
		cygterm_closing,
		cygterm_receive,
		cygterm_sent,
		cygterm_accepting
	};
	Local local;
	const char *command;
	char cmdline[2 * MAX_PATH];
	int cport;
	const char *err;
	int cmdlinelen;

	cygterm_debug("top");

	local = snew(struct cygterm_backend_data);
	local->fn = &fn_table;
	local->a = NULL;
	local->s = NULL;
	local->cfg = *cfg;
	local->editing = 0;
	local->echoing = 0;
	local->exitcode = 0;
	*backend_handle = local;

	local->frontend = frontend_handle;

	/* set up listen socket for communication with child */
	cygterm_debug("setupCygTerm");

	/* let sk use INADDR_LOOPBACK and let WinSock choose a port */
	local->a = sk_newlistener(0, 0, (Plug)local, 1, ADDRTYPE_IPV4);
	if ((err = sk_socket_error(local->a)) != NULL)
		goto fail_free;

	/* now, get the port that WinSock chose */
	/* XXX: Is there another function in PuTTY to do this? */
	cygterm_debug("getting port");
	cport = sk_getport(local->a);
	if (cport == -1) {
		err = "Failed to get port number for cthelper";
		goto fail_close;
	}

	if (strchr(local->cfg.termtype, ' ')) {
		err = "term type contains spaces";
		goto fail_close;
	}

	/*  Build cthelper command line */
	cmdlinelen = sprintf(cmdline, CTHELPER" %u %s ", cport, local->cfg.termtype);
	cmdlinelen += makeAttributes(cmdline + cmdlinelen, &local->cfg);

	command = cfg->cygcmd;
	cygterm_debug("command is :%s:", command);
	/*  A command of  "."  or  "-"  tells us to pass no command arguments to
	 *  cthelper which will then run the user's shell under Cygwin.  */
	if ((command[0]=='-'||command[0]=='.') && command[1]=='\0')
		;
	else if (cmdlinelen + strlen(command) + 2 > sizeof cmdline) {
		err = "command is too long";
		goto fail_close;
	}
	else {
		cmdlinelen += sprintf(cmdline + cmdlinelen, " %s", command);
	}

	/* Add the Cygwin /bin path to the PATH. */
	if (cfg->cygautopath) {
		char *cygwinBinPath = getCygwinBin();
		if (!cygwinBinPath) {
			/* we'll try anyway */
			cygterm_debug("cygwin bin directory not found");
		}
		else {
			cygterm_debug("found cygwin directory: %s", cygwinBinPath);
			appendPath(cygwinBinPath);
			sfree(cygwinBinPath);
		}
	}

	cygterm_debug("starting cthelper: %s", cmdline);
	if ((err = spawnChild(cmdline, &local->pi, &local->ctl)))
		goto fail_close;

	/*  This should be set to the local hostname, Apparently, realhost is used
	 *  only to set the window title.
	 */
	strcpy(*realhost = smalloc(sizeof CYGTERM_NAME), CYGTERM_NAME);
	cygterm_debug("OK");
	return 0;

fail_close:
	sk_close(local->a);
fail_free:
	sfree(local);
	return err;
}
Beispiel #8
0
static void do_clearmodes(User * u)
{
	int i, all;
	int count;		/* For saving ban info */
	char *s;
	char *argv[3];
	char *chan;
	Channel *c;
	Ban **bans;		/* For saving ban info */
	struct c_userlist *cu, *next;

	chan = strtok(NULL, " ");
	all = 0;

	if (!chan) {
		syntax_error(s_OperServ, u, "CLEARMODES",
		    OPER_CLEARMODES_SYNTAX);
	} else if (!(c = findchan(chan))) {
		notice_lang(s_OperServ, u, CHAN_X_NOT_IN_USE, chan);
	} else if (c->bouncy_modes) {
		notice_lang(s_OperServ, u, OPER_BOUNCY_MODES_U_LINE);
		return;
	} else {
		s = strtok(NULL, " ");

		if (s) {
			if (stricmp(s, "ALL") == 0) {
				all = 1;
			} else {
				syntax_error(s_OperServ, u, "CLEARMODES",
				    OPER_CLEARMODES_SYNTAX);
				return;
			}
		}

		if (WallOSClearmodes) {
			wallops(s_OperServ, "%s used CLEARMODES%s on %s",
			    u->nick, all ? " ALL" : "", chan);
		}

		if (all) {
			/* Clear mode +o */
			for (cu = c->chanops; cu; cu = next) {
				next = cu->next;
				argv[0] = sstrdup(chan);
				argv[1] = sstrdup("-o");
				argv[2] = sstrdup(cu->user->nick);
				send_cmd(MODE_SENDER(s_ChanServ),
				    "MODE %s %s :%s", argv[0], argv[1],
				    argv[2]);
				do_cmode(s_ChanServ, 3, argv);
				free(argv[2]);
				free(argv[1]);
				free(argv[0]);
			}

			/* Clear mode +v */
			for (cu = c->voices; cu; cu = next) {
				next = cu->next;
				argv[0] = sstrdup(chan);
				argv[1] = sstrdup("-v");
				argv[2] = sstrdup(cu->user->nick);
				send_cmd(MODE_SENDER(s_ChanServ),
				    "MODE %s %s :%s", argv[0], argv[1],
				    argv[2]);
				do_cmode(s_ChanServ, 3, argv);
				free(argv[2]);
				free(argv[1]);
				free(argv[0]);
			}
		}

		/* Clear modes */
		send_cmd(MODE_SENDER(s_OperServ),
		    "MODE %s -ciklmMnOpsRt :%s", chan,
		    c->key ? c->key : "");
		argv[0] = sstrdup(chan);
		argv[1] = sstrdup("-ciklmMnOpsRt");
		argv[2] = c->key ? c->key : sstrdup("");
		do_cmode(s_OperServ, 2, argv);
		free(argv[0]);
		free(argv[1]);
		free(argv[2]);
		c->key = NULL;
		c->limit = 0;

		/* Clear bans */
		count = c->bancount;
		bans = smalloc(sizeof(Ban *) * count);

		for (i = 0; i < count; i++) {
			bans[i] = smalloc(sizeof(Ban));
			bans[i]->mask = sstrdup(c->newbans[i]->mask);
		}
		for (i = 0; i < count; i++) {
			argv[0] = sstrdup(chan);
			argv[1] = sstrdup("-b");
			argv[2] = bans[i]->mask;
			send_cmd(MODE_SENDER(s_OperServ), "MODE %s %s :%s",
			    argv[0], argv[1], argv[2]);
			do_cmode(s_OperServ, 3, argv);
			free(argv[2]);
			free(argv[1]);
			free(argv[0]);
			free(bans[i]);
		}
		free(bans);

		if (all) {
			notice_lang(s_OperServ, u, OPER_CLEARMODES_ALL_DONE,
			    chan);
		} else {
			notice_lang(s_OperServ, u, OPER_CLEARMODES_DONE,
			    chan);
		}
	}
}
Beispiel #9
0
void
userinit(void)
{
	void *v;
	Proc *p;
	Segment *s;
	Page *pg;

	p = newproc();
	p->pgrp = newpgrp();
	p->egrp = smalloc(sizeof(Egrp));
	p->egrp->ref = 1;
	p->fgrp = dupfgrp(nil);
	p->rgrp = newrgrp();
	p->procmode = 0640;

	kstrdup(&eve, "");
	kstrdup(&p->text, "*init*");
	kstrdup(&p->user, eve);

	p->fpstate = FPinit;
	fpoff();

	/*
	 * Kernel Stack
	 *
	 * N.B. make sure there's enough space for syscall to check
	 *	for valid args and 
	 *	4 bytes for gotolabel's return PC
	 */
	p->sched.pc = (ulong)init0;
	p->sched.sp = (ulong)p->kstack+KSTACK-(sizeof(Sargs)+BY2WD);

	/*
	 * User Stack
	 *
	 * N.B. cannot call newpage() with clear=1, because pc kmap
	 * requires up != nil.  use tmpmap instead.
	 */
	s = newseg(SG_STACK, USTKTOP-USTKSIZE, USTKSIZE/BY2PG);
	p->seg[SSEG] = s;
	pg = newpage(0, 0, USTKTOP-BY2PG);
	v = tmpmap(pg);
	memset(v, 0, BY2PG);
	segpage(s, pg);
	bootargs(v);
	tmpunmap(v);

	/*
	 * Text
	 */
	s = newseg(SG_TEXT, UTZERO, 1);
	s->flushme++;
	p->seg[TSEG] = s;
	pg = newpage(0, 0, UTZERO);
	memset(pg->cachectl, PG_TXTFLUSH, sizeof(pg->cachectl));
	segpage(s, pg);
	v = tmpmap(pg);
	memset(v, 0, BY2PG);
	memmove(v, initcode, sizeof initcode);
	tmpunmap(v);

	ready(p);
}
Beispiel #10
0
void 
wbpcover (
    int n_left,		/* number of vertices on left side */
    int n_right,		/* number of vertices on right side */
    int *pointers,		/* start/stop of adjacency lists */
    int *indices,		/* adjacency list for each vertex */
    int *vweight,		/* vertex weights */
    int *psep_size,		/* returned size of separator */
    int *psep_weight,		/* returned weight of separator */
    int **psep_nodes		/* list of separator nodes */
)
{
    extern int DEBUG_COVER;	/* debug flag for this routine */
    int      *touched;		/* flags for each vertex */
    int      *resid;		/* remaining, unmatched vertex weight */
    int      *flow;		/* flow on each right->left edge */
    int      *sep_nodes;	/* list of separator nodes */
    int       sep_size;		/* returned size of separator */
    int       sep_weight;	/* returned weight of separator */
    int       nedges;		/* number of edges in bipartite graph */
    int       i, j;		/* loop counter */
    int       wleft, wright, wedges;

    void      confirm_cover();

if (DEBUG_COVER) {
    printf("-> Entering wbpcover, nleft = %d, nright = %d, 2*nedges = %d\n",
	n_left, n_right, pointers[n_left+n_right]-pointers[0]);

    wleft = wright = 0;
    wedges = 0;
    for (i = 0; i < n_left; i++) {
	wleft += vweight[i];
	for (j = pointers[i]; j < pointers[i + 1]; j++)  {
	    wedges += vweight[i] * vweight[indices[j]];
	}
    }
    for (i = n_left; i < n_left + n_right; i++) {
	wright += vweight[i];
	for (j = pointers[i]; j < pointers[i + 1]; j++)  {
	    wedges += vweight[i] * vweight[indices[j]];
	}
    }
    printf("    Corresponds to unweighted, nleft = %d, nright = %d, 2*nedges = %d\n",
	wleft, wright, wedges);
}

    nedges = pointers[n_left + n_right] - pointers[0];

    resid = smalloc((n_left + n_right) * sizeof(int));
    touched = smalloc((n_left + n_right) * sizeof(int));
    flow = smalloc((nedges + 1) * sizeof(int));


    /* Not a matching.  I can be connected to multiple nodes. */
    bpflow(n_left, n_right, pointers, indices, vweight, resid, flow, touched);

    reachability(n_left, n_right, pointers, indices, resid, flow, touched);


    /* Separator includes untouched nodes on left, touched on right. */
    /* Left separator nodes if unconnected to unmatched right node via */
    /* augmenting path, right separator nodes otherwise. */

    /* First count the separator size for malloc. */
    sep_size = 0;
    for (i = 0; i < n_left; i++) {
	if (!touched[i]) {
	    sep_size++;
	}
    }
    for (i = n_left; i < n_left + n_right; i++) {
	if (touched[i]) {
	    sep_size++;
	}
    }

    sep_nodes = smalloc((sep_size + 1) * sizeof(int));

    sep_size = sep_weight = 0;
    for (i = 0; i < n_left; i++) {
	if (!touched[i]) {
	    sep_nodes[sep_size++] = i;
	    sep_weight += vweight[i];
	}
    }
    for (i = n_left; i < n_left + n_right; i++) {
	if (touched[i]) {
	    sep_nodes[sep_size++] = i;
	    sep_weight += vweight[i];
	}
    }

    sep_nodes[sep_size] = 0;

    *psep_size = sep_size;
    *psep_weight = sep_weight;
    *psep_nodes = sep_nodes;

/* Check the answer. */
if (DEBUG_COVER) {
confirm_cover(n_left, n_right, pointers, indices, flow, vweight, resid,
		             sep_size, sep_nodes);
}

    sfree(flow);
    sfree(touched);
    sfree(resid);
}
Beispiel #11
0
void 
mapper (
    struct vtx_data **graph,	/* data structure with vertex weights */
    double **xvecs,		/* continuous indicator vectors */
    int nvtxs,		/* number of vtxs in graph */
    int *active,		/* space for nmyvals ints */
    int *sets,			/* returned processor assignment for my vtxs */
    int ndims,		/* number of dimensions being divided into */
    int cube_or_mesh,		/* 0 => hypercube, d => d-dimensional mesh */
    int nsets,		/* number of sets to divide into */
    int mediantype,		/* type of eigenvector partitioning to use */
    double *goal,			/* desired set sizes */
    int vwgt_max		/* largest vertex weight */
)
{
    double    temp_goal[2];	/* combined set goals if using option 1. */
    double    wbelow;		/* weight of vertices with negative values */
    double    wabove;		/* weight of vertices with positive values */
    int      *temp_sets;	/* sets vertices get assigned to */
    int       vweight;		/* weight of a vertex */
    int       using_vwgts;	/* are vertex weights being used? */
    int       bits;		/* bits for assigning set numbers */
    int       i, j;		/* loop counters */

    void      median(), rec_median_k(), rec_median_1(), median_assign();
    void      map2d(), map3d();

    /* NOTE: THIS EXPECTS XVECS, NOT YVECS! */

    using_vwgts = (vwgt_max != 1);

    if (ndims == 1 && mediantype == 1)
	mediantype = 3;		/* simpler call than normal option 1. */

    if (mediantype == 0) {	/* Divide at zero instead of median. */
	bits = 1;
	temp_sets = smalloc((nvtxs + 1) * sizeof(int));
	for (j = 1; j <= nvtxs; j++)
	    sets[j] = 0;

	for (i = 1; i <= ndims; i++) {
	    temp_goal[0] = temp_goal[1] = 0;
	    for (j = 0; j < (1 << ndims); j++) {
		if (bits & j)
		    temp_goal[1] += goal[j];
		else
		    temp_goal[0] += goal[j];
	    }
	    bits <<= 1;

	    wbelow = wabove = 0;
	    vweight = 1;
	    for (j = 1; j <= nvtxs; j++) {
		if (using_vwgts)
		    vweight = graph[j]->vwgt;
		if (xvecs[i][j] < 0)
		    wbelow += vweight;
		else if (xvecs[i][j] > 0)
		    wabove += vweight;
	    }

	    median_assign(graph, xvecs[i], nvtxs, temp_goal, using_vwgts, temp_sets,
			  wbelow, wabove, (double) 0.0);

	    for (j = 1; j <= nvtxs; j++)
		sets[j] = (sets[j] << 1) + temp_sets[j];
	}
    }

    else if (mediantype == 1) {	/* Divide using min-cost assignment. */
	if (ndims == 2)
	    map2d(graph, xvecs, nvtxs, sets, goal, vwgt_max);
	else if (ndims == 3)
	    map3d(graph, xvecs, nvtxs, sets, goal, vwgt_max);
    }


    else if (mediantype == 2) {	/* Divide recursively using medians. */
	rec_median_k(graph, xvecs, nvtxs, active, ndims, cube_or_mesh, goal,
		     using_vwgts, sets);
    }

    else if (mediantype == 3) {	/* Cut with independent medians => unbalanced. */
	bits = 1;
	temp_sets = smalloc((nvtxs + 1) * sizeof(int));
	for (j = 1; j <= nvtxs; j++)
	    sets[j] = 0;

	for (i = 1; i <= ndims; i++) {
	    temp_goal[0] = temp_goal[1] = 0;
	    for (j = 0; j < (1 << ndims); j++) {
		if (bits & j)
		    temp_goal[1] += goal[j];
		else
		    temp_goal[0] += goal[j];
	    }
	    bits <<= 1;

	    median(graph, xvecs[i], nvtxs, active, temp_goal, using_vwgts, temp_sets);
	    for (j = 1; j <= nvtxs; j++)
		sets[j] = (sets[j] << 1) + temp_sets[j];
	}
	sfree(temp_sets);
    }

    if (mediantype == 4) {	/* Stripe the domain. */
	rec_median_1(graph, xvecs[1], nvtxs, active, cube_or_mesh, nsets,
		     goal, using_vwgts, sets, TRUE);
    }
}
Beispiel #12
0
static long
ipread(Chan *ch, void *a, long n, vlong off)
{
	int r;
	Conv *c;
	Proto *x;
	char *p, *s;
	Fs *f;
	ulong offset = off;

	f = ipfs[ch->dev];

	p = a;
	switch(TYPE(ch->qid)) {
	default:
		error(Eperm);
	case Qprotodir:
	case Qtopdir:
	case Qconvdir:
		return devdirread(ch, a, n, 0, 0, ipgen);
	case Qarp:
		error(Eperm);	/* TO DO */
	case Qndb:
		return readstr(off, a, n, f->ndb);
	case Qctl:
		sprint(up->genbuf, "%lud", CONV(ch->qid));
		return readstr(offset, p, n, up->genbuf);
	case Qremote:
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		sprint(up->genbuf, "%I!%d\n", c->raddr, c->rport);
		return readstr(offset, p, n, up->genbuf);
	case Qlocal:
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		sprint(up->genbuf, "%I!%d\n", c->laddr, c->lport);
		return readstr(offset, p, n, up->genbuf);
	case Qstatus:
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		s = smalloc(Statelen);
		if(waserror()){
			free(s);
			nexterror();
		}
		snprint(s, Statelen, "%s\n", ipstates[c->state]);
		n = readstr(offset, p, n, s);
		poperror();
		free(s);
		return n;
	case Qdata:
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		if(c->sfd < 0)
			error(Ehungup);
		if(c->headers) {
			if(n < c->headers)
				error(Ebadarg);
			p = a;
			r = so_recv(c->sfd, p + c->headers, n - c->headers, p, c->headers);
			if(r > 0)
				r += c->headers;
		} else
			r = so_recv(c->sfd, a, n, nil, 0);
		if(r < 0)
			oserror();
		return r;
	case Qstats:
		error("stats not implemented");
		return n;
	}
}
Beispiel #13
0
static long
ipread(Chan *ch, void *a, long n, vlong off)
{
	Conv *c;
	Proto *x;
	char *buf, *p;
	long rv;
	Fs *f;
	ulong offset = off;

	f = ipfs[ch->dev];

	p = a;
	switch(TYPE(ch->qid)) {
	default:
		error(Eperm);
	case Qtopdir:
	case Qprotodir:
	case Qconvdir:
		return devdirread(ch, a, n, 0, 0, ipgen);
	case Qarp:
		return arpread(f->arp, a, offset, n);
 	case Qbootp:
 		return bootpread(a, offset, n);
 	case Qndb:
		return readstr(offset, a, n, f->ndb);
	case Qiproute:
		return routeread(f, a, offset, n);
	case Qipselftab:
		return ipselftabread(f, a, offset, n);
	case Qlog:
		return netlogread(f, a, offset, n);
	case Qctl:
		buf = smalloc(16);
		snprint(buf, 16, "%lud", CONV(ch->qid));
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	case Qremote:
		buf = smalloc(Statelen);
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		if(x->remote == nil) {
			snprint(buf, Statelen, "%I!%d\n", c->raddr, c->rport);
		} else {
			(*x->remote)(c, buf, Statelen-2);
		}
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	case Qlocal:
		buf = smalloc(Statelen);
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		if(x->local == nil) {
			snprint(buf, Statelen, "%I!%d\n", c->laddr, c->lport);
		} else {
			(*x->local)(c, buf, Statelen-2);
		}
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	case Qstatus:
		buf = smalloc(Statelen);
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		(*x->state)(c, buf, Statelen-2);
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	case Qdata:
		c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
		return qread(c->rq, a, n);
	case Qerr:
		c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
		return qread(c->eq, a, n);
	case Qsnoop:
		c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
		return qread(c->sq, a, n);
	case Qstats:
		x = f->p[PROTO(ch->qid)];
		if(x->stats == nil)
			error("stats not implemented");
		buf = smalloc(Statelen);
		(*x->stats)(x, buf, Statelen);
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	}
}
static int  cmd_send(void *handle, char *buf, int len)
{
	pcmd_backend_data local = handle;
	DWORD writed;
	char *tmp = smalloc(len+1);
	memset(tmp,0,len+1);
	if( !handle || !buf || !len )
		return 0;
	if( strstr(buf, "\r\n") == NULL )
	{
		if( len == 1 && buf[0] == 127 ) //backspace
		{
			int l = strlen(local->semdcmd);
			if( l != 0 )
			{
				from_backend(local->frontend, 0, buf, len);
				l = l-1;
			}
			local->semdcmd[l] = '\0';
			local->bufsize = 1;
		}
		else if( buf[0] == 27 )
		{
			// left || right || up || down
			char c = buf[2];
			if( c == 'A' || c == 'B' ) // up and down
			{
				cmd_rollback_until_none(local);
				if( local->historycount != 0 )
				{
					char* his_buf = (c == 'A') ? cmd_get_previeous_histroy(local) : cmd_get_next_histroy(local);
					strcpy(local->semdcmd, his_buf);
					from_backend(local->frontend, 0, local->semdcmd, strlen(local->semdcmd));
				}
			}
			else
			{
				from_backend(local->frontend, 0, buf+1, 2);
				memcpy(tmp, buf+1, 2);
				strcat(local->semdcmd, tmp);
				local->bufsize = 2;
			}
		}
		else
		{
			from_backend(local->frontend, 0, buf, len);
			memcpy(tmp, buf, len);
			strcat(local->semdcmd, tmp);
			local->bufsize = len;
		}
		
	}
	else
	{

		char sendcmd[MAX_CMD_BUF];
		strcpy(sendcmd, local->semdcmd);
		cmd_rollback_until_none(local);

		WriteFile(local->m_hStdInWrite, sendcmd, strlen(sendcmd), &writed, NULL);
		local->bufsize = writed;
		WriteFile(local->m_hStdInWrite, "\n", 1, &writed, NULL);
		local->bufsize += writed;
		cmd_add_histroy(local, sendcmd);
		local->current_histroy = NULL;
	}

	sfree(tmp);
	return local->bufsize;
}
Beispiel #15
0
Proc*
newproc(void)
{
	Mach *m = machp();
	Proc *p;

	p = psalloc();

	p->state = Scheding;
	p->psstate = "New";
	p->mach = 0;
	p->qnext = 0;
	p->nchild = 0;
	p->nwait = 0;
	p->waitq = 0;
	p->parent = 0;
	p->pgrp = 0;
	p->egrp = 0;
	p->fgrp = 0;
	p->rgrp = 0;
	p->pdbg = 0;
	p->kp = 0;
	if(m->externup != nil && m->externup->procctl == Proc_tracesyscall)
		p->procctl = Proc_tracesyscall;
	else
		p->procctl = 0;
	p->syscalltrace = nil;
	p->notepending = 0;
	p->ureg = 0;
	p->privatemem = 0;
	p->noswap = 0;
	p->errstr = p->errbuf0;
	p->syserrstr = p->errbuf1;
	p->errbuf0[0] = '\0';
	p->errbuf1[0] = '\0';
	p->nlocks = 0;
	p->delaysched = 0;
	p->trace = 0;
	kstrdup(&p->user, "*nouser");
	kstrdup(&p->text, "*notext");
	kstrdup(&p->args, "");
	p->nargs = 0;
	p->setargs = 0;
	memset(p->seg, 0, sizeof p->seg);
	p->pid = incref(&pidalloc);
	pshash(p);
	p->noteid = incref(&noteidalloc);
	if(p->pid <= 0 || p->noteid <= 0)
		panic("pidalloc");
	if(p->kstack == 0){
		p->kstack = smalloc(KSTACK);
		*(uintptr_t*)p->kstack = STACKGUARD;
	}

	/* sched params */
	p->mp = 0;
	p->wired = 0;
	procpriority(p, PriNormal, 0);
	p->cpu = 0;
	p->lastupdate = sys->ticks*Scaling;
	p->edf = nil;

	p->ntrap = 0;
	p->nintr = 0;
	p->nsyscall = 0;
	p->nactrap = 0;
	p->nacsyscall = 0;
	p->nicc = 0;
	p->actime = 0ULL;
	p->tctime = 0ULL;
	p->ac = nil;
	p->nfullq = 0;
	p->req = nil;
	p->resp = nil;
	memset(&p->PMMU, 0, sizeof p->PMMU);
	return p;
}
Beispiel #16
0
/*
 * This function returns the absolute path to the executable it is running in.
 *
 * The implementation follows http://stackoverflow.com/a/933996/712014
 *
 * Returned value must be freed by the caller.
 */
char *get_exe_path(const char *argv0) {
	size_t destpath_size = 1024;
	size_t tmp_size = 1024;
	char *destpath = smalloc(destpath_size);
	char *tmp = smalloc(tmp_size);


#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
	/* Linux and Debian/kFreeBSD provide /proc/self/exe */
#if defined(__linux__) || defined(__FreeBSD_kernel__)
	const char *exepath = "/proc/self/exe";
#elif defined(__FreeBSD__)
	const char *exepath = "/proc/curproc/file";
#endif
	ssize_t linksize;

	while ((linksize = readlink(exepath, destpath, destpath_size)) == destpath_size) {
		destpath_size = destpath_size * 2;
		destpath = srealloc(destpath, destpath_size);
	}
	if (linksize != -1) {
		/* readlink() does not NULL-terminate strings, so we have to. */
		destpath[linksize] = '\0';
		free(tmp);
		return destpath;
	}
#endif

	/* argv[0] is most likely a full path if it starts with a slash. */
	if (argv0[0] == '/') {
		free(tmp);
		free(destpath);
		return sstrdup(argv0);
	}

	/* if argv[0] contains a /, prepend the working directory */
	if (strchr(argv0, '/') != NULL) {
		char *retgcwd;
		while ((retgcwd = getcwd(tmp, tmp_size)) == NULL && errno == ERANGE) {
			tmp_size = tmp_size * 2;
			tmp = srealloc(tmp, tmp_size);
		}
		if (retgcwd != NULL) {
			free(destpath);
			sasprintf(&destpath, "%s/%s", tmp, argv0);
			free(tmp);
			return destpath;
		}
	}

	/* Fall back to searching $PATH (or _CS_PATH in absence of $PATH). */
	char *path = getenv("PATH");
	if (path == NULL) {
		/* _CS_PATH is typically something like "/bin:/usr/bin" */
		while (confstr(_CS_PATH, tmp, tmp_size) > tmp_size) {
			tmp_size = tmp_size * 2;
			tmp = srealloc(tmp, tmp_size);
		}
		sasprintf(&path, ":%s", tmp);
	} else {
		path = strdup(path);
	}
	const char *component;
	char *str = path;
	while (1) {
		if ((component = strtok(str, ":")) == NULL)
			break;
		str = NULL;
		free(destpath);
		sasprintf(&destpath, "%s/%s", component, argv0);
		/* Of course this is not 100% equivalent to actually exec()ing the
		 * binary, but meh. */
		if (access(destpath, X_OK) == 0) {
			free(path);
			free(tmp);
			return destpath;
		}
	}
	free(destpath);
	free(path);
	free(tmp);

	/* Last resort: maybe it’s in /usr/bin? */
	return sstrdup("/usr/bin/i3-nagbar");
}
Beispiel #17
0
void
pexit(char *exitstr, int freemem)
{
	Mach *m = machp();
	Proc *p;
	Segment **s, **es;
	int32_t utime, stime;
	Waitq *wq, *f, *next;
	Fgrp *fgrp;
	Egrp *egrp;
	Rgrp *rgrp;
	Pgrp *pgrp;
	Chan *dot;

	if(0 && m->externup->nfullq > 0)
		iprint(" %s=%d", m->externup->text, m->externup->nfullq);
	if(0 && m->externup->nicc > 0)
		iprint(" [%s nicc %ud tctime %ulld actime %ulld]\n",
			m->externup->text, m->externup->nicc, m->externup->tctime, m->externup->actime);
	if(m->externup->syscalltrace != nil)
		free(m->externup->syscalltrace);
	m->externup->syscalltrace = nil;
	m->externup->alarm = 0;

	if (m->externup->tt)
		timerdel(m->externup);
	if(m->externup->trace)
		proctrace(m->externup, SDead, 0);

	/* nil out all the resources under lock (free later) */
	qlock(&m->externup->debug);
	fgrp = m->externup->fgrp;
	m->externup->fgrp = nil;
	egrp = m->externup->egrp;
	m->externup->egrp = nil;
	rgrp = m->externup->rgrp;
	m->externup->rgrp = nil;
	pgrp = m->externup->pgrp;
	m->externup->pgrp = nil;
	dot = m->externup->dot;
	m->externup->dot = nil;
	qunlock(&m->externup->debug);


	if(fgrp)
		closefgrp(fgrp);
	if(egrp)
		closeegrp(egrp);
	if(rgrp)
		closergrp(rgrp);
	if(dot)
		cclose(dot);
	if(pgrp)
		closepgrp(pgrp);

	/*
	 * if not a kernel process and have a parent,
	 * do some housekeeping.
	 */
	if(m->externup->kp == 0) {
		p = m->externup->parent;
		if(p == 0) {
			if(exitstr == 0)
				exitstr = "unknown";
			//die("bootprocessdeath");
			panic("boot process died: %s", exitstr);
		}

		while(waserror())
			;

		wq = smalloc(sizeof(Waitq));
		poperror();

		wq->w.pid = m->externup->pid;
		utime = m->externup->time[TUser] + m->externup->time[TCUser];
		stime = m->externup->time[TSys] + m->externup->time[TCSys];
		wq->w.time[TUser] = tk2ms(utime);
		wq->w.time[TSys] = tk2ms(stime);
		wq->w.time[TReal] = tk2ms(sys->machptr[0]->ticks - m->externup->time[TReal]);
		if(exitstr && exitstr[0])
			snprint(wq->w.msg, sizeof(wq->w.msg), "%s %d: %s",
				m->externup->text, m->externup->pid, exitstr);
		else
			wq->w.msg[0] = '\0';

		lock(&p->exl);
		/*
		 * Check that parent is still alive.
		 */
		if(p->pid == m->externup->parentpid && p->state != Broken) {
			p->nchild--;
			p->time[TCUser] += utime;
			p->time[TCSys] += stime;
			/*
			 * If there would be more than 128 wait records
			 * processes for my parent, then don't leave a wait
			 * record behind.  This helps prevent badly written
			 * daemon processes from accumulating lots of wait
			 * records.
		 	 */
			if(p->nwait < 128) {
				wq->next = p->waitq;
				p->waitq = wq;
				p->nwait++;
				wq = nil;
				wakeup(&p->waitr);
			}
		}
		unlock(&p->exl);
		if(wq)
			free(wq);
	}

	if(!freemem)
		addbroken(m->externup);

	qlock(&m->externup->seglock);
	es = &m->externup->seg[NSEG];
	for(s = m->externup->seg; s < es; s++) {
		if(*s) {
			putseg(*s);
			*s = 0;
		}
	}
	qunlock(&m->externup->seglock);

	lock(&m->externup->exl);		/* Prevent my children from leaving waits */
	psunhash(m->externup);
	m->externup->pid = 0;
	wakeup(&m->externup->waitr);
	unlock(&m->externup->exl);

	for(f = m->externup->waitq; f; f = next) {
		next = f->next;
		free(f);
	}

	/* release debuggers */
	qlock(&m->externup->debug);
	if(m->externup->pdbg) {
		wakeup(&m->externup->pdbg->sleep);
		m->externup->pdbg = 0;
	}
	qunlock(&m->externup->debug);

	/* Sched must not loop for these locks */
	lock(&procalloc);
	lock(&pga);

	stopac();
	edfstop(m->externup);
	m->externup->state = Moribund;
	sched();
	panic("pexit");
}
static int
startline_parsereq (startline_t * dest, char *buf, char **headers)
{
  char *p1;
  char *p2;
  char *requesturi;
  int i;

  dest->sipmethod = NULL;
  dest->statuscode = NULL;
  dest->reasonphrase = NULL;

  /* The first token is the method name: */
  p2 = strchr (buf, ' ');
  if (p2 == NULL)
    return -1;
  if (p2-buf==0)
    {
      OSIP_TRACE (osip_trace
		  (__FILE__, __LINE__, OSIP_ERROR, NULL,
		   "No space allowed here\n"));
      return -1;
    }
  dest->sipmethod = (char *) smalloc (p2 - buf + 1);
  sstrncpy (dest->sipmethod, buf, p2 - buf);

  /* The second token is a sip-url or a uri: */
  p1 = strchr (p2 + 2, ' ');	/* no space allowed inside sip-url */
  if (p1 - p2 < 2)
    return -1;
  requesturi = (char *) smalloc (p1 - p2);
  sstrncpy (requesturi, p2 + 1, (p1 - p2 - 1));
  sclrspace (requesturi);

  url_init (&(dest->rquri));
  i = url_parse (dest->rquri, requesturi);
  sfree (requesturi);
  if (i == -1)
    return -1;

  /* find the the version and the beginning of headers */
  {
    char *hp = p1;

    while ((*hp != '\r') && (*hp != '\n'))
      {
	if (*hp)
	  hp++;
	else
	  {
	    OSIP_TRACE (osip_trace
			(__FILE__, __LINE__, OSIP_ERROR, NULL,
			 "No crlf found\n"));
	    return -1;
	  }
      }
    if (hp - p1 < 2)
      return -1;
    dest->sipversion = (char *) smalloc (hp - p1);
    sstrncpy (dest->sipversion, p1 + 1, (hp - p1 - 1));

    hp++;
    if ((*hp) && ('\r' == hp[-1]) && ('\n' == hp[0]))
      hp++;
    (*headers) = hp;
  }
  return 0;
}
Beispiel #19
0
Datei: scp.c Projekt: rdebath/sgt
/*
 *  We will copy local files to a remote server.
 */
static void toremote(int argc, char *argv[])
{
    char *src, *targ, *host, *user;
    char *cmd;
    int i;

    targ = argv[argc-1];

    /* Separate host from filename */
    host = targ;
    targ = colon(targ);
    if (targ == NULL)
	bump("targ == NULL in toremote()");
    *targ++ = '\0';
    if (*targ == '\0')
	targ = ".";
    /* Substitute "." for emtpy target */

    /* Separate host and username */
    user = host;
    host = strrchr(host, '@');
    if (host == NULL) {
	host = user;
	user = NULL;
    } else {
	*host++ = '\0';
	if (*user == '\0')
	    user = NULL;
    }

    if (argc == 2) {
	/* Find out if the source filespec covers multiple files
	 if so, we should set the targetshouldbedirectory flag */
	HANDLE fh;
	WIN32_FIND_DATA fdat;
	if (colon(argv[0]) != NULL)
	    bump("%s: Remote to remote not supported", argv[0]);
	fh = FindFirstFile(argv[0], &fdat);
	if (fh == INVALID_HANDLE_VALUE)
	    bump("%s: No such file or directory\n", argv[0]);
	if (FindNextFile(fh, &fdat))
	    targetshouldbedirectory = 1;
	FindClose(fh);
    }

    cmd = smalloc(strlen(targ) + 100);
    sprintf(cmd, "scp%s%s%s%s -t %s",
	    verbose ? " -v" : "",
	    recursive ? " -r" : "",
	    preserve ? " -p" : "",
	    targetshouldbedirectory ? " -d" : "",
	    targ);
    do_cmd(host, user, cmd);
    sfree(cmd);

    (void) response();

    for (i = 0; i < argc - 1; i++) {
	HANDLE dir;
	WIN32_FIND_DATA fdat;
	src = argv[i];
	if (colon(src) != NULL) {
	    fprintf(stderr,
		    "%s: Remote to remote not supported\n", src);
	    errs++;
	    continue;
	}
	dir = FindFirstFile(src, &fdat);
	if (dir == INVALID_HANDLE_VALUE) {
	    run_err("%s: No such file or directory", src);
	    continue;
	}
	do {
	    char *last;
	    char namebuf[2048];
	    if (strlen(src) + strlen(fdat.cFileName) >=
		sizeof(namebuf)) {
		fprintf(stderr, "%s: Name too long", src);
		continue;
	    }
	    strcpy(namebuf, src);
	    if ((last = strrchr(namebuf, '/')) == NULL)
		last = namebuf;
	    else
		last++;
	    if (strrchr(last, '\\') != NULL)
		last = strrchr(last, '\\') + 1;
	    if (last == namebuf && strrchr(namebuf, ':') != NULL)
		last = strchr(namebuf, ':') + 1;
	    strcpy(last, fdat.cFileName);
	    source(namebuf);
	} while (FindNextFile(dir, &fdat));
	FindClose(dir);
    }
}
int
msg_handle_multiple_values (sip_t * sip, char *hname, char *hvalue)
{
  int i;
  char *ptr;			/* current location of the search */
  char *comma;			/* This is the separator we are elooking for */
  char *beg;			/* beg of a header */
  char *end;			/* end of a header */
  char *quote1;			/* first quote of a pair of quotes   */
  char *quote2;			/* second quuote of a pair of quotes */


  beg = hvalue;
  end = NULL;
  ptr = hvalue;
  if (hvalue == NULL)
    {
      i = msg_set_header (sip, hname, hvalue);
      if (i == -1)
	return -1;
      return 0;
    }

  comma = strchr (ptr, ',');


  stolowercase (hname);

  if (comma == NULL || (strncmp (hname, "date", 4) == 0 && strlen (hname) == 4 )
      || strncmp (hname, "organization", 12) == 0 || (strncmp (hname, "to", 2) == 0 && strlen (hname) == 2) || (strncmp (hname, "from", 4) == 0 && strlen (hname) == 4)	/* AMD: BUG fix */
      || strncmp (hname, "call-id", 7) == 0 || (strncmp (hname, "cseq", 4) == 0 && strlen (hname) == 4)	/* AMD: BUG fix */
      || strncmp (hname, "subject", 7) == 0 || strncmp (hname, "user-agent", 10) == 0 || strncmp (hname, "server", 6) == 0 || strncmp (hname, "www-authenticate", 16) == 0	/* AMD: BUG fix */
      || strncmp (hname, "authentication-info", 19) == 0 || strncmp (hname, "proxy-authenticate", 20) == 0 || strncmp (hname, "proxy-authorization", 19) == 0 || strncmp (hname, "proxy-authentication-info", 25) == 0	/* AMD: BUG fix */
      || strncmp (hname, "authorization", 13) == 0)
    /* there is no multiple header! likely      */
    /* to happen most of the time...            */
    /* or hname is a TEXT-UTF8-TRIM and may     */
    /* contain a comma. this is not a separator */
    /* THIS DOES NOT WORK FOR UNKNOWN HEADER!!!! */
    {
      i = msg_set_header (sip, hname, hvalue);
      if (i == -1)
	return -1;
      return 0;
    }

  quote2 = NULL;
  while (comma != NULL)
    {
      quote1 = quote_find (ptr);
      if (quote1 != NULL)
	{
	  quote2 = quote_find (quote1 + 1);
	  if (quote2 == NULL)
	    return -1;		/* quotes comes by pair */
	  ptr = quote2 + 1;
	}

      if ((quote1 == NULL) || (quote1 > comma))
	{
	  end = comma;
	  comma = strchr (comma + 1, ',');
	  ptr = comma + 1;
	}
      else if ((quote1 < comma) && (quote2 < comma))
	{			/* quotes are located before the comma, */
	  /* continue the search for next quotes  */
	  ptr = quote2 + 1;
	}
      else if ((quote1 < comma) && (comma < quote2))
	{			/* if comma is inside the quotes... */
	  /* continue with the next comma.    */
	  ptr = quote2 + 1;
	  comma = strchr (ptr, ',');
	  if (comma == NULL)
	    /* this header last at the end of the line! */
	    {			/* this one does not need an allocation... */
	      if (strlen (beg) < 2)
		return 0;	/* empty header */
	      sclrspace (beg);
	      i = msg_set_header (sip, hname, beg);
	      if (i == -1)
		return -1;
	      return 0;
	    }
	}

      if (end != NULL)
	{
	  char *avalue;

	  if (end - beg + 1 < 2)
	    return -1;
	  avalue = (char *) smalloc (end - beg + 1);
	  sstrncpy (avalue, beg, end - beg);
	  sclrspace (avalue);
	  /* really store the header in the sip structure */
	  i = msg_set_header (sip, hname, avalue);
	  sfree (avalue);
	  if (i == -1)
	    return -1;
	  beg = end + 1;
	  end = NULL;
	  if (comma == NULL)
	    /* this header last at the end of the line! */
	    {			/* this one does not need an allocation... */
	      if (strlen (beg) < 2)
		return 0;	/* empty header */
	      sclrspace (beg);
	      i = msg_set_header (sip, hname, beg);
	      if (i == -1)
		return -1;
	      return 0;
	    }
	}
    }
  return -1;			/* if comma is NULL, we should have already return 0 */
}
Beispiel #21
0
static
struct conn_t *conn_new(struct sockaddr_in *raddr, struct sockaddr_in *laddr) {
    struct conn_t *c;
    int lsize, errnosave;
    struct sockaddr_in tmp;

    c = smalloc(sizeof(*c));
    memset(c, 0, sizeof(*c));
    c->state = CONN_NEW;
    INIT_LIST_HEAD(&c->reqs);

    if ((c->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
	errnosave = errno;
	syslog(LOG_ERR, "socket: %s", strerror(errno));
	free(c);
	errno = errnosave;
	return 0;
    }

    /* If this is not the first connection, do a non-blocking connect */
    if (!list_empty(&clist))
	set_non_block(c->fd);

    tmp = *laddr;		/* use a temp here because
				 * bindresvport writes it. */
    if (laddr->sin_port ||
	bindresvport(c->fd, &tmp) == -1) {
	    syslog(LOG_ERR, "bindresvport: %s (ignoring)", strerror(errno));
	    /* If we specified a port or failed to bind to a reserved
	     * port for some reason, try a normal bind. */
	    if (bind(c->fd, (struct sockaddr *) laddr, sizeof(*laddr)) == -1) {
		errnosave = errno;
		syslog(LOG_ERR, "bind(%s:%d): %s (ignoring)",
		       inet_ntoa(laddr->sin_addr), ntohs(laddr->sin_port),
		       strerror(errno));
		close(c->fd);
		free(c);
		errno = errnosave;
		return 0;
	    }
    }

    if (verbose)
	syslog(LOG_INFO, "Connecting to %s:%d...",
	       inet_ntoa(raddr->sin_addr), ntohs(raddr->sin_port));

    if (connect(c->fd, (struct sockaddr *) raddr, sizeof(*raddr)) == -1) {
	if (errno != EINPROGRESS) {
	    errnosave = errno;
	    syslog(LOG_ERR, "connect(%s:%d): %s",
		   inet_ntoa(raddr->sin_addr), ntohs(raddr->sin_port),
		   strerror(errno));
	    close(c->fd);
	    free(c);
	    errno = errnosave;
	    return 0;
	}
    }

    /* Make note of our local address */
    lsize = sizeof(c->laddr);
    getsockname(c->fd, (struct sockaddr *)&c->laddr, &lsize);
    c->raddr = *raddr;

    /* Prime output buffer with version information and cookie */
    conn_send_version(c);

    set_keep_alive(c->fd);
    set_no_delay(c->fd);
    set_non_block(c->fd);

    /* Append to list of connections */
    list_add_tail(&c->list, &clist);
    return c;
}
/* set all headers */
int
msg_headers_parse (sip_t * sip, char *start_of_header, char **body)
{
  char *colon_index;		/* index of ':' */
  char *hname;
  char *hvalue;
  char *end_of_header;
  int i;

  for (;;)
    {
      i = find_next_crlf (start_of_header, &end_of_header);
      if (i == -1)
	{
	  OSIP_TRACE (osip_trace
		      (__FILE__, __LINE__, OSIP_ERROR, NULL,
		       "End of header Not found\n"));
	  return -1;		/* this is an error case!     */
	}
      if (end_of_header[0] == '\0')
	{			/* final CRLF is missing */
	  OSIP_TRACE (osip_trace
		      (__FILE__, __LINE__, OSIP_ERROR, NULL,
		       "SIP message does not end with CRLFCRLF\n"));
	  return -1;
	}
      /* find the header name */
      colon_index = strchr (start_of_header, ':');
      if (colon_index == NULL)
	{
	  OSIP_TRACE (osip_trace
		      (__FILE__, __LINE__, OSIP_ERROR, NULL,
		       "End of header Not found\n"));
	  return -1;		/* this is also an error case */
	}
      if (colon_index - start_of_header + 1 < 2)
	return -1;
      if (end_of_header <= colon_index)
	{
	  OSIP_TRACE (osip_trace
		      (__FILE__, __LINE__, OSIP_ERROR, NULL,
		       "Malformed message\n"));
	  return -1;
	}
      hname = (char *) smalloc (colon_index - start_of_header + 1);
      sstrncpy (hname, start_of_header, colon_index - start_of_header);
      sclrspace (hname);

      {
	char *end;

	/* END of header is (end_of_header-2) if header separation is CRLF */
	/* END of header is (end_of_header-1) if header separation is CR or LF */
	if ((end_of_header[-2] == '\r') || (end_of_header[-2] == '\n'))
	  end = end_of_header - 2;
	else
	  end = end_of_header - 1;
	if ((end) - colon_index < 2)
	  hvalue = NULL;	/* some headers (subject) can be empty */
	else
	  {
	    hvalue = (char *) smalloc ((end) - colon_index);
	    sstrncpy (hvalue, colon_index + 1, (end) - colon_index - 1);
	    sclrspace (hvalue);
	  }
      }

      /* hvalue MAY contains multiple value. In this case, they   */
      /* are separated by commas. But, a comma may be part of a   */
      /* quoted-string ("here, and there" is an example where the */
      /* comma is not a separator!) */
      i = msg_handle_multiple_values (sip, hname, hvalue);

      sfree (hname);
      sfree (hvalue);
      if (i == -1)
	{
	  OSIP_TRACE (osip_trace
		      (__FILE__, __LINE__, OSIP_ERROR, NULL,
		       "End of header Not found\n"));
	  return -1;
	}

      /* the list of headers MUST always end with  */
      /* CRLFCRLF (also CRCR and LFLF are allowed) */
      if ((end_of_header[0] == '\r') || (end_of_header[0] == '\n'))
	{
	  *body = end_of_header;
	  return 0;		/* end of header found        */
	}
      /* continue on the next header */
      start_of_header = end_of_header;
    }

/* Unreachable code
 OSIP_TRACE (osip_trace
	      (__FILE__, __LINE__, OSIP_BUG, NULL,
	       "This code cannot be reached\n")); */
  return -1;
}
Beispiel #23
0
/*
 * Rewrite the results of a directory read to reflect current
 * name space bindings and mounts.  Specifically, replace
 * directory entries for bind and mount points with the results
 * of statting what is mounted there.  Except leave the old names.
 */
static int32_t
mountfix(Chan *c, uint8_t *op, int32_t n, int32_t maxn)
{
	Proc *up = externup();
	char *name;
	int nbuf;
	Chan *nc;
	Mhead *mh;
	Mount *mount;
	usize dirlen, nname, r, rest;
	int32_t l;
	uint8_t *buf, *e, *p;
	Dir d;

	p = op;
	buf = nil;
	nbuf = 0;
	for(e=&p[n]; p+BIT16SZ<e; p+=dirlen){
		dirlen = dirfixed(p, e, &d);
		if(dirlen == 0)
			break;
		nc = nil;
		mh = nil;
		if(findmount(&nc, &mh, d.type, d.dev, d.qid)){
			/*
			 * If it's a union directory and the original is
			 * in the union, don't rewrite anything.
			 */
			for(mount=mh->mount; mount; mount=mount->next)
				if(eqchanddq(mount->to, d.type, d.dev, d.qid, 1))
					goto Norewrite;

			name = dirname(p, &nname);
			/*
			 * Do the stat but fix the name.  If it fails,
			 * leave old entry.
			 * BUG: If it fails because there isn't room for
			 * the entry, what can we do?  Nothing, really.
			 * Might as well skip it.
			 */
			if(buf == nil){
				buf = smalloc(4096);
				nbuf = 4096;
			}
			if(waserror())
				goto Norewrite;
			l = nc->dev->stat(nc, buf, nbuf);
			r = dirsetname(name, nname, buf, l, nbuf);
			if(r == BIT16SZ)
				error("dirsetname");
			poperror();

			/*
			 * Shift data in buffer to accomodate new entry,
			 * possibly overflowing into rock.
			 */
			rest = e - (p+dirlen);
			if(r > dirlen){
				while(p+r+rest > op+maxn){
					mountrock(c, p, &e);
					if(e == p){
						dirlen = 0;
						goto Norewrite;
					}
					rest = e - (p+dirlen);
				}
			}
			if(r != dirlen){
				memmove(p+r, p+dirlen, rest);
				dirlen = r;
				e = p+dirlen+rest;
			}

			/*
			 * Rewrite directory entry.
			 */
			memmove(p, buf, r);

		    Norewrite:
			cclose(nc);
			putmhead(mh);
		}
	}
	if(buf)
		free(buf);

	if(p != e)
		error("oops in mountfix");

	return e-op;
}
/* internal method to parse the body */
int
msg_body_parse (sip_t * sip, char *start_of_buf, char **next_body)
{
  char *start_of_body;
  char *end_of_body;
  char *tmp;
  int i;

  char *sep_boundary;
  generic_param_t *ct_param;

  /* if MIME-Version: does not exist we just have */
  /* to deal with one body and no header... */
  if (sip->mime_version == NULL)
    {				/* Mime-Version header does NOT exist */
      if (sip->content_type == NULL)
	return 0;		/* no body is attached */
      else
	{
	  size_t body_len;

	  if (start_of_buf[0] == '\0')
	    return -1;		/* final CRLF is missing */
	  /* get rid of the first CRLF */
	  if ('\r' == start_of_buf[0])
	    {
	      if ('\n' == start_of_buf[1])
		start_of_body = start_of_buf + 2;
	      else
		start_of_body = start_of_buf + 1;
	    }
	  else if ('\n' == start_of_buf[0])
	    start_of_body = start_of_buf + 1;
	  else
	    return -1;		/* message does not end with CRLFCRLF, CRCR or LFLF */

	  if (sip->contentlength != NULL)
	    body_len = satoi (sip->contentlength->value);
	  else
	    {			/* if content_length does not exist, set it. */
	      char *tmp = smalloc (8);

	      if (tmp == NULL)
		return -1;
	      body_len = strlen (start_of_body);
	      sprintf (tmp, "%i", body_len);
	      i = msg_setcontent_length (sip, tmp);
	      sfree (tmp);
	      if (i != 0)
		return -1;
	    }

	  if (body_len > strlen (start_of_body))	/* we do not receive the */
	    return -1;		/* complete message      */
	  /* end_of_body = start_of_body + strlen(start_of_body); */
	  end_of_body = start_of_body + body_len;
	  tmp = smalloc (end_of_body - start_of_body + 2);
	  if (tmp == NULL)
	    return -1;
	  sstrncpy (tmp, start_of_body, end_of_body - start_of_body);

	  i = msg_setbody (sip, tmp);
	  sfree (tmp);
	  if (i != 0)
	    return -1;
	  return 0;
	}
    }

  /* find the boundary */
  i = generic_param_getbyname (sip->content_type->gen_params,
			       "boundary", &ct_param);
  if (i != 0)
    return -1;

  if (ct_param == NULL)
    return -1;
  if (ct_param->gvalue == NULL)
    return -1;			/* No boundary but multiple headers??? */

  sep_boundary = (char *) smalloc (strlen (ct_param->gvalue) + 3);
  sprintf (sep_boundary, "--%s", ct_param->gvalue);

  *next_body = NULL;
  start_of_body = start_of_buf;
  for (;;)
    {
      i = find_next_occurence (sep_boundary, start_of_body, &start_of_body);
      if (i == -1)
	{
	  sfree (sep_boundary);
	  return -1;
	}
      i =
	find_next_occurence (sep_boundary,
			     start_of_body + strlen (sep_boundary),
			     &end_of_body);
      if (i == -1)
	{
	  sfree (sep_boundary);
	  return -1;
	}

      /* this is the real beginning of body */
      start_of_body = start_of_body + strlen (sep_boundary) + 2;

      tmp = smalloc (end_of_body - start_of_body + 1);
      sstrncpy (tmp, start_of_body, end_of_body - start_of_body);

      i = msg_setbody_mime (sip, tmp);
      sfree (tmp);
      if (i == -1)
	{
	  sfree (sep_boundary);
	  return -1;
	}

      if (strncmp (end_of_body + strlen (sep_boundary), "--", 2) == 0)
	{			/* end of all bodies */
	  *next_body = end_of_body;
	  sfree (sep_boundary);
	  return 0;
	}
      /* continue on the next body */
      start_of_body = end_of_body;
    }
  /* Unreachable code */
  /* sfree (sep_boundary); */
  return -1;
}
Beispiel #25
0
void get_sesslist(int allocate)
{
    static char otherbuf[2048];
    static char *buffer;
    int buflen, bufsize, i;
    char *p, *ret;
    void *handle;

    if (allocate) {

	buflen = bufsize = 0;
	buffer = NULL;
	if ((handle = enum_settings_start())) {
	    do {
		ret = enum_settings_next(handle, otherbuf, sizeof(otherbuf));
		if (ret) {
		    int len = strlen(otherbuf) + 1;
		    if (bufsize < buflen + len) {
			bufsize = buflen + len + 2048;
			buffer = srealloc(buffer, bufsize);
		    }
		    strcpy(buffer + buflen, otherbuf);
		    buflen += strlen(buffer + buflen) + 1;
		}
	    } while (ret);
	    enum_settings_finish(handle);
	}
	buffer = srealloc(buffer, buflen + 1);
	buffer[buflen] = '\0';

	/*
	 * Now set up the list of sessions. Note that "Default
	 * Settings" must always be claimed to exist, even if it
	 * doesn't really.
	 */

	p = buffer;
	nsessions = 1;		       /* "Default Settings" counts as one */
	while (*p) {
	    if (strcmp(p, "Default Settings"))
		nsessions++;
	    while (*p)
		p++;
	    p++;
	}

	sessions = smalloc((nsessions + 1) * sizeof(char *));
	sessions[0] = "Default Settings";
	p = buffer;
	i = 1;
	while (*p) {
	    if (strcmp(p, "Default Settings"))
		sessions[i++] = p;
	    while (*p)
		p++;
	    p++;
	}

	qsort(sessions, i, sizeof(char *), sessioncmp);
    } else {
	sfree(buffer);
	sfree(sessions);
    }
}
Beispiel #26
0
int main(int argc, char* argv[]) {
    FILE* F;
    MSA *msa;
    int *msa_gap_patterns = NULL;
    HMM *hmm = NULL;
    TreeNode *tree = NULL;
    int i, input_format = SS, msa_idx, quiet_mode = FALSE,
           ncats, nmsas, ncats_unspooled, indel_nseqs = -1;
    String *msa_fname, *gff_fname;
    List *gff_fname_list = NULL, *msa_fname_list = NULL,
          *msa_length_list = NULL, *model_indels_str = NULL;
    Matrix *traincounts = NULL;
    Vector *begcounts = NULL, *statecounts = NULL;
    CategoryMap *cm = NULL;
    char c;
    GapPatternMap *gpm = NULL;
    GFF_Set *gff;
    char *reverse_groups_tag = NULL;

    while ((c = getopt(argc, argv, "i:g:c:m:M:R:I:n:t:P:G:qh")) != -1) {
        switch(c) {
        case 'i':
            input_format = msa_str_to_format(optarg);
            if (input_format == -1)
                die("ERROR: bad alignment format.\n");
            break;
        case 'g':
            gff_fname_list = get_arg_list(optarg);
            break;
        case 'c':
            cm = cm_new_string_or_file(optarg);
            break;
        case 'm':
            msa_fname_list = get_arg_list(optarg);
            break;
        case 'M':
            msa_length_list = str_list_as_int(get_arg_list(optarg));
            break;
        case 'R':
            reverse_groups_tag = optarg;
            break;
        case 'I':
            model_indels_str = get_arg_list(optarg);
            break;
        case 'n':
            indel_nseqs = get_arg_int(optarg);
            break;
        case 't':
            if (optarg[0] == '(')     /* in this case, assume topology given
                                   at command line */
                tree = tr_new_from_string(optarg);
            else
                tree = tr_new_from_file(phast_fopen(optarg, "r"));
            break;
        case 'q':
            quiet_mode = TRUE;
            break;
        case 'h':
            print_usage();
            exit(0);
        case '?':
            die("ERROR: unrecognized option.\n\nType 'hmm_train -h' for usage.\n");
        }
    }

    if (msa_fname_list == NULL)
        die("ERROR: -m required.  Type 'hmm_train -h' for usage.\n");
    if (gff_fname_list == NULL)
        die("ERROR: -g required in training mode.  Type 'hmm_train -h' for usage.\n");
    if (msa_length_list != NULL && msa_fname_list != NULL)
        die("ERROR: -m and -M are mutually exclusive.  Type 'hmm_train -h' for usage.\n");
    if (model_indels_str != NULL && tree == NULL)
        die("ERROR: -I requires -t.  Type 'hmm_train -h' for usage.\n");
    if (cm == NULL)
        die("ERROR: category map required.\n");

    set_seed(-1);

    ncats = cm->ncats + 1;
    ncats_unspooled = cm->unspooler != NULL ? cm->unspooler->nstates_unspooled :
                      ncats;
    nmsas = (msa_length_list != NULL ? lst_size(msa_length_list) :
             lst_size(msa_fname_list));

    if (model_indels_str != NULL) {
        if (tree == NULL)
            die("ERROR: tree is NULL\n");  /*FIXME: indel_ncats broken */
        gpm = gp_create_gapcats(cm, model_indels_str, tree, FALSE);
        ncats = cm->ncats + 1;    /* numbers will change */
        ncats_unspooled = cm->unspooler == NULL ? ncats :
                          cm->unspooler->nstates_unspooled;
    }

    /* allocate memory for storage of "training paths" */
    traincounts = mat_new(ncats_unspooled, ncats_unspooled);
    statecounts = vec_new(ncats_unspooled);
    begcounts = vec_new(ncats_unspooled);
    mat_zero(traincounts);
    vec_zero(statecounts);
    vec_zero(begcounts);


    /* create skeleton of new HMM. */
    hmm = hmm_new_nstates(ncats_unspooled, 0, 0);

    /* Main loop: consider each MSA in turn */
    for (msa_idx = 0; msa_idx < nmsas; msa_idx++) {
        if (msa_fname_list != NULL) {
            msa_fname = (String*)lst_get_ptr(msa_fname_list, msa_idx);
            F = phast_fopen(msa_fname->chars, "r");
            if (!quiet_mode)
                fprintf(stderr, "Reading alignment from %s ...\n",
                        F == stdin ? "stdin" : msa_fname->chars);
            msa = msa_new_from_file(F, NULL);
            phast_fclose(F);

        }
        else {                      /* only lengths of alignments specified */
            msa = msa_new(NULL, NULL, 0, lst_get_int(msa_length_list, msa_idx), NULL);
            /* just a shell in this case */
        }

        gff_fname = (String*)lst_get_ptr(gff_fname_list, msa_idx);
        if (!quiet_mode)
            fprintf(stderr, "Reading annotations from %s ...\n", gff_fname->chars);
        gff = gff_read_set(phast_fopen(gff_fname->chars, "r"));

        /* convert GFF to coordinate frame of alignment */
        if (msa_length_list == NULL) {
            if (!quiet_mode)
                fprintf(stderr, "Mapping annotations to alignment ...\n");
            msa_map_gff_coords(msa, gff, 1, 0, 0); /* assume seq 1 is ref */
        }

        if (model_indels_str != NULL) {
            if (!quiet_mode)
                fprintf(stderr, "Obtaining gap patterns ...\n");
            msa_gap_patterns = smalloc(msa->length * sizeof(int));
            gp_set_phylo_patterns(gpm, msa_gap_patterns, msa);
        }

        /* at this point, we don't actually need the alignment anymore;
           if using ordered suff stats (likely with large data sets),
           can free them now, to avoid running out of memory */
        if (msa->ss != NULL) {
            ss_free(msa->ss);
            msa->ss = NULL;
        }

        if (reverse_groups_tag != NULL) {
            if (!quiet_mode)
                fprintf(stderr, "Reverse complementing features on negative strand (group by '%s') ...\n",
                        reverse_groups_tag);
            /* we don't need to reverse complement the whole alignment --
               just the gff and possibly the gap pattern array (pass a
               NULL msa) */
            gff_group(gff, reverse_groups_tag);
            msa_reverse_compl_feats(NULL, gff, msa_gap_patterns);
        }

        if (!quiet_mode)
            fprintf(stderr, "Labeling sites by category ...\n");
        msa_label_categories(msa, gff, cm);

        gff_free_set(gff);

        if (model_indels_str != NULL) {
            if (!quiet_mode)
                fprintf(stderr, "Remapping categories according to gap patterns ...\n");

            if (indel_nseqs > 0 && indel_nseqs != msa->nseqs) {
                /* in this case, we'll simply reassign non-trivial gap
                   patterns randomly.  This will achieve the desired
                   effect with minimal coding, as long as the number of
                   sites is not too small (the indel model is probably
                   useless anyway if the number is small) */
                int pat, newpat;
                int npatterns = 4 * indel_nseqs - 5;
                int complex_allowed[cm->ncats+1];
                List *no_complex_names, *no_complex_nums;

                if (!quiet_mode)
                    fprintf(stderr, "(target number of sequences: %d)\n", indel_nseqs);

                /* set up index indicating by cat no. whether complex gaps
                   are allowed */
                for (i = 0; i < ncats; i++) complex_allowed[i] = 1;
                no_complex_names = lst_new_ptr(10);
                str_split(str_new_charstr(NO_COMPLEX), ",", no_complex_names);
                no_complex_nums = cm_get_category_list(cm, no_complex_names, 1);
                for (i = 0; i < lst_size(no_complex_nums); i++)
                    complex_allowed[lst_get_int(no_complex_nums, i)] = 0;
                lst_free(no_complex_nums);
                lst_free_strings(no_complex_names);
                lst_free(no_complex_names);

                /* now reassign all non-null numbers */
                for (i = 0; i < msa->length; ) {
                    if ((pat = msa_gap_patterns[i]) != 0) {
                        if (complex_allowed[msa->categories[i]])
                            newpat = 1 + ((double)npatterns * unif_rand());
                        /* random number in interval [1, npatterns] */
                        else
                            newpat = 1 + ((double)(npatterns-1) * unif_rand());
                        /* random number in interval [1,npatterns-1]
                           (excludes complex gap pattern) */
                        for (; i < msa->length && msa_gap_patterns[i] == pat; i++)
                            msa_gap_patterns[i] = newpat; /* change for whole sequence */
                    }
                    else i++;
                }
            }

            /* obtain gapped category number for each site */
            for (i = 0; i < msa->length; i++)
                if (gpm->cat_x_pattern_to_gapcat[msa->categories[i]] != NULL)
                    msa->categories[i] = gpm->cat_x_pattern_to_gapcat[msa->categories[i]][msa_gap_patterns[i]];
        }

        if (!quiet_mode)
            fprintf(stderr, "Unspooling categories ...\n");
        cm_spooled_to_unspooled(cm, msa->categories, msa->length);

        if (!quiet_mode)
            fprintf(stderr, "Collecting training data ...\n");
        hmm_train_update_counts(traincounts, statecounts, begcounts,
                                msa->categories, msa->length,
                                ncats_unspooled);

        if (msa_gap_patterns != NULL) sfree(msa_gap_patterns);
        msa_free(msa);
    }

    /* now train HMM, using cumulative data */
    hmm_train_from_counts(hmm, traincounts, NULL, statecounts, NULL,
                          begcounts, NULL);

    /* if modeling indels, adjust begin transitions so probability is
       distributed among different "gap pattern" states that all
       correspond to the same ungapped state (category); this helps
       avoid problems that occur when training on a few large sequences
       (e.g., whole chromosomes) and then testing on many shorter ones */
    if (model_indels_str != NULL) {
        double tprob[gpm->ncats];
        int nst[gpm->ncats];  /* total prob and number of states per
                             spooled, ungapped category */
        for (i = 0; i < gpm->ncats; i++) tprob[i] = nst[i] = 0;
        for (i = 0; i < hmm->nstates; i++) {
            if (vec_get(hmm->begin_transitions, i) > 0)
                /* have to go from unspooled space to spooled space, then to
                   ungapped space (HMM states correspond to unspooled,
                   gapped categories).  Note that states with nonzero begin
                   probs shouldn't be conditioned on other states. */
                tprob[gpm->gapcat_to_cat[cm_unspooled_to_spooled_cat(cm, i)]] +=
                    vec_get(hmm->begin_transitions, i);
            nst[gpm->gapcat_to_cat[cm_unspooled_to_spooled_cat(cm, i)]]++;
        }
        for (i = 0; i < hmm->nstates; i++)
            if (tprob[gpm->gapcat_to_cat[cm_unspooled_to_spooled_cat(cm, i)]] > 0)
                vec_set(hmm->begin_transitions, i,
                        tprob[gpm->gapcat_to_cat[cm_unspooled_to_spooled_cat(cm, i)]] /
                        nst[gpm->gapcat_to_cat[cm_unspooled_to_spooled_cat(cm, i)]]);
        /* (uniform prior) */
    }

    /* write trained HMM */
    hmm_print(stdout, hmm);

    if (!quiet_mode) fprintf(stderr, "Done.\n");

    return 0;
}
Beispiel #27
0
/*
 * Initiate the outputs list
 *
 */
void init_outputs(void) {
    outputs = smalloc(sizeof(struct outputs_head));
    SLIST_INIT(outputs);
}
Beispiel #28
0
long
w_ifstat(Ether* ether, void* a, long n, ulong offset)
{
	Ctlr *ctlr = (Ctlr*) ether->ctlr;
	char *k, *p;
	int i, l, txid;

	ether->oerrs = ctlr->ntxerr;
	ether->crcs = ctlr->nrxfcserr;
	ether->frames = 0;
	ether->buffs = ctlr->nrxdropnobuf;
	ether->overflows = 0;

	//
	// Offset must be zero or there's a possibility the
	// new data won't match the previous read.
	//
	if(n == 0 || offset != 0)
		return 0;

	p = smalloc(READSTR);
	l = 0;

	PRINTSTAT("Signal: %d\n", ctlr->signal-149);
	PRINTSTAT("Noise: %d\n", ctlr->noise-149);
	PRINTSTAT("SNR: %ud\n", ctlr->signal-ctlr->noise);
	PRINTSTAT("Interrupts: %lud\n", ctlr->nints);
	PRINTSTAT("Double Interrupts: %lud\n", ctlr->ndoubleint);
	PRINTSTAT("TxPackets: %lud\n", ctlr->ntx);
	PRINTSTAT("RxPackets: %lud\n", ctlr->nrx);
	PRINTSTAT("TxErrors: %lud\n", ctlr->ntxerr);
	PRINTSTAT("RxErrors: %lud\n", ctlr->nrxerr);
	PRINTSTAT("TxRequests: %lud\n", ctlr->ntxrq);
	PRINTSTAT("AllocEvs: %lud\n", ctlr->nalloc);
	PRINTSTAT("InfoEvs: %lud\n", ctlr->ninfo);
	PRINTSTAT("InfoDrop: %lud\n", ctlr->nidrop);
	PRINTSTAT("WatchDogs: %lud\n", ctlr->nwatchdogs);
	PRINTSTAT("Ticks: %ud\n", ctlr->ticks);
	PRINTSTAT("TickIntr: %ud\n", ctlr->tickintr);
	k = ((ctlr->state & Attached) ? "attached" : "not attached");
	PRINTSTAT("Card %s", k);
	k = ((ctlr->state & Power) ? "on" : "off");
	PRINTSTAT(", power %s", k);
	k = ((ctlr->txbusy)? ", txbusy" : "");
	PRINTSTAT("%s\n", k);

	if(ctlr->hascrypt){
		PRINTSTR("Keys: ");
		for (i = 0; i < WNKeys; i++){
			if(ctlr->keys.keys[i].len == 0)
				PRINTSTR("none ");
			else if(SEEKEYS == 0)
				PRINTSTR("set ");
			else
				PRINTSTAT("%s ", ctlr->keys.keys[i].dat);
		}
		PRINTSTR("\n");
	}

	// real card stats
	ilock(ctlr);
	PRINTSTR("\nCard stats: \n");
	PRINTSTAT("Status: %ux\n", csr_ins(ctlr, WR_Sts));
	PRINTSTAT("Event status: %ux\n", csr_ins(ctlr, WR_EvSts));
	i = ltv_ins(ctlr, WTyp_Ptype);
	PRINTSTAT("Port type: %d\n", i);
	PRINTSTAT("Transmit rate: %d\n", ltv_ins(ctlr, WTyp_TxRate));
	PRINTSTAT("Current Transmit rate: %d\n",
		ltv_ins(ctlr, WTyp_CurTxRate));
	PRINTSTAT("Channel: %d\n", ltv_ins(ctlr, WTyp_Chan));
	PRINTSTAT("AP density: %d\n", ltv_ins(ctlr, WTyp_ApDens));
	PRINTSTAT("Promiscuous mode: %d\n", ltv_ins(ctlr, WTyp_Prom));
	if(i == WPTypeAdHoc)
		PRINTSTAT("SSID name: %s\n", ltv_inname(ctlr, WTyp_NetName));
	else {
		Wltv ltv;
		PRINTSTAT("Current name: %s\n", ltv_inname(ctlr, WTyp_CurName));
		ltv.type = WTyp_BaseID;
		ltv.len = 4;
		if(w_inltv(ctlr, &ltv))
			print("#l%d: unable to read base station mac addr\n", ether->ctlrno);
		l += snprint(p+l, READSTR-l, "Base station: %2.2x%2.2x%2.2x%2.2x%2.2x%2.2x\n",
			ltv.addr[0], ltv.addr[1], ltv.addr[2], ltv.addr[3], ltv.addr[4], ltv.addr[5]);
	}
	PRINTSTAT("Net name: %s\n", ltv_inname(ctlr, WTyp_WantName));
	PRINTSTAT("Node name: %s\n", ltv_inname(ctlr, WTyp_NodeName));
	if(ltv_ins(ctlr, WTyp_HasCrypt) == 0)
		PRINTSTR("WEP: not supported\n");
	else {
		if(ltv_ins(ctlr, WTyp_Crypt) == 0)
			PRINTSTR("WEP: disabled\n");
		else{
			PRINTSTR("WEP: enabled\n");
			k = ((ctlr->xclear)? "excluded": "included");
			PRINTSTAT("Clear packets: %s\n", k);
			txid = ltv_ins(ctlr, WTyp_TxKey);
			PRINTSTAT("Transmit key id: %d\n", txid);
		}
	}
	iunlock(ctlr);

	PRINTSTAT("ntxuframes: %lud\n", ctlr->ntxuframes);
	PRINTSTAT("ntxmframes: %lud\n", ctlr->ntxmframes);
	PRINTSTAT("ntxfrags: %lud\n", ctlr->ntxfrags);
	PRINTSTAT("ntxubytes: %lud\n", ctlr->ntxubytes);
	PRINTSTAT("ntxmbytes: %lud\n", ctlr->ntxmbytes);
	PRINTSTAT("ntxdeferred: %lud\n", ctlr->ntxdeferred);
	PRINTSTAT("ntxsretries: %lud\n", ctlr->ntxsretries);
	PRINTSTAT("ntxmultiretries: %lud\n", ctlr->ntxmultiretries);
	PRINTSTAT("ntxretrylimit: %lud\n", ctlr->ntxretrylimit);
	PRINTSTAT("ntxdiscards: %lud\n", ctlr->ntxdiscards);
	PRINTSTAT("nrxuframes: %lud\n", ctlr->nrxuframes);
	PRINTSTAT("nrxmframes: %lud\n", ctlr->nrxmframes);
	PRINTSTAT("nrxfrags: %lud\n", ctlr->nrxfrags);
	PRINTSTAT("nrxubytes: %lud\n", ctlr->nrxubytes);
	PRINTSTAT("nrxmbytes: %lud\n", ctlr->nrxmbytes);
	PRINTSTAT("nrxfcserr: %lud\n", ctlr->nrxfcserr);
	PRINTSTAT("nrxdropnobuf: %lud\n", ctlr->nrxdropnobuf);
	PRINTSTAT("nrxdropnosa: %lud\n", ctlr->nrxdropnosa);
	PRINTSTAT("nrxcantdecrypt: %lud\n", ctlr->nrxcantdecrypt);
	PRINTSTAT("nrxmsgfrag: %lud\n", ctlr->nrxmsgfrag);
	PRINTSTAT("nrxmsgbadfrag: %lud\n", ctlr->nrxmsgbadfrag);
	USED(l);
	n = readstr(offset, a, n, p);
	free(p);
	return n;
}
Beispiel #29
0
//------------------------------------------------------------------
// Allocates memory and constructs the gauge fixing matrices
//------------------------------------------------------------------
void AlgFixGauge::run()
{
  const char *fname = "run";
  VRB.Func(cname,fname);

  // Set the Lattice pointer
  //----------------------------------------------------------------
  Lattice& lat = AlgLattice();

  // Set up arguments
  //----------------------------------------------------------------
  FixGaugeType fix = alg_fix_gauge_arg->fix_gauge_kind;
  int start = alg_fix_gauge_arg->hyperplane_start;
  int step = alg_fix_gauge_arg->hyperplane_step;
  int num = alg_fix_gauge_arg->hyperplane_num;
  int lattice_dir_size=0;
  int *h_planes = 0;

  // If coulomb gauge
  //----------------------------------------------------------------
  if( (fix == FIX_GAUGE_COULOMB_X) ||
      (fix == FIX_GAUGE_COULOMB_Y) ||
      (fix == FIX_GAUGE_COULOMB_Z) ||
      (fix == FIX_GAUGE_COULOMB_T)  ){ 

      switch(fix){
      case FIX_GAUGE_COULOMB_X:
	  lattice_dir_size = GJP.XnodeSites() * GJP.Xnodes();
	  break;
      case FIX_GAUGE_COULOMB_Y:
	  lattice_dir_size = GJP.YnodeSites() * GJP.Ynodes();
	  break;
      case FIX_GAUGE_COULOMB_Z:
	  lattice_dir_size = GJP.ZnodeSites() * GJP.Znodes();
	  break;
      case FIX_GAUGE_COULOMB_T:
	  lattice_dir_size = GJP.TnodeSites() * GJP.Tnodes();
	  break;
      case FIX_GAUGE_NONE:
      case FIX_GAUGE_LANDAU:
	  break;
      }

    if(start+step*(num-1) >= lattice_dir_size)
	ERR.General(cname, fname,
		    "The coordinate of the last hyperplane (%d+%d*%d) is greater than the global lattice size.", 
		    start, step, num-1, lattice_dir_size);

    h_planes = (int *) smalloc(num * sizeof(int));
    if(h_planes == 0) ERR.Pointer(cname,fname, "h_planes");
    VRB.Smalloc(cname,fname, "h_planes", h_planes, num * sizeof(int));
    
    for(int i=0; i<num; i++) h_planes[i] = start + step * i;

  }

  // Allocate gauge fixing matrices and set them to 1
  //----------------------------------------------------------------
  lat.FixGaugeAllocate(fix, num, h_planes);


  // Calculate the gauge fixing matrices
  //----------------------------------------------------------------
// added to make it possible to explicitly bypass gauge fixin:w
  if ( alg_fix_gauge_arg->max_iter_num > 0 ) 
  lat.FixGauge(alg_fix_gauge_arg->stop_cond, 
	       alg_fix_gauge_arg->max_iter_num);


  VRB.Sfree(cname,fname, "h_planes",h_planes);
  sfree(h_planes);

}
Beispiel #30
0
/*
头格式       编码gbk
Int 头大小
Int 内容大小
byte 静态页版本格式 0 or 1, 1:deadtime
byte 是否有效
long 过期时间毫秒
long 生成时间毫秒
long 页号
byte 站类型  0 私有 1共享 >1 会员
int  关键词长度
byte[] 关键词
int ig号长度
byte[] ig
Int  鉴权方式  0 不鉴权,1特殊页面鉴权,2php 特殊页面鉴权3,会员鉴权
int  额外参数的长度
byte[] 额外参数{PageAuth:{sid:,appid,authid:},GroupAuth:{sid,appid,authid}}
byte[] 文件内容
*/
page_t *
file_read_path(char *path)
{
  tbuf mt = {0, NULL};
  
  if (tbuf_read(&mt, path)) {
    char *strpos;
    uint32_t strlen;
    stream_t s = {0, mt.len, (uint8_t*)mt.data};
    size_t min = 2 * sizeof(uint32_t);
    if (mt.len < min) {
      tbuf_close(&mt);
      return NULL;
    }
    uint32_t hlen = readu32(&s);
    uint32_t blen = readu32(&s);
    if (mt.len != min+hlen+blen) {
      tbuf_close(&mt);
      return NULL;
    }

    /* |<-- page_t -->|<-- body data -->|<-- head strings -->| */
    /* about 32 bytes in head is not for strings */
    size_t plen = sizeof(page_t)+blen+hlen-32;
    page_t *page = (page_t*)smalloc(plen);
    page->page_len = plen;
    page->body_len = blen;
    page->body = (char*)page+sizeof(page_t);
    memcpy(page->body, mt.data+2*sizeof(uint32_t)+hlen, page->body_len);
    strpos = (char*)page->body + blen;

    page_head_t *head = &page->head;
    head->version = readu8(&s);
    switch(head->version) {
    case 0:
      head->valid = readu8(&s);
      head->time_expire = readu64(&s);
      head->time_create = readu64(&s);
      head->time_dead   = head->time_expire+(uint64_t)24*3600*1000;
      head->page_no = readu64(&s);
      head->type = readu8(&s);

      strlen = readu32(&s);
      readarr(&s, strpos, strlen);
      *(strpos+strlen) = 0;
      head->keyword = strpos;
      strpos += strlen+1;

      strlen = readu32(&s);
      readarr(&s, strpos, strlen);
      *(strpos+strlen) = 0;
      head->ig = strpos;
      strpos += strlen+1;

      head->auth_type = readu32(&s);

      strlen = readu32(&s);
      readarr(&s, strpos, strlen);
      *(strpos+strlen) = 0;
      head->param = strpos;
      strpos += strlen+1;
      break;
    case 1:
      head->valid = readu8(&s);
      head->time_expire = readu64(&s);
      head->time_create = readu64(&s);
      head->time_dead   = readu64(&s);
      head->page_no = readu64(&s);
      head->type = readu8(&s);

      strlen = readu32(&s);
      readarr(&s, strpos, strlen);
      *(strpos+strlen) = 0;
      head->keyword = strpos;
      strpos += strlen+1;

      strlen = readu32(&s);
      readarr(&s, strpos, strlen);
      *(strpos+strlen) = 0;
      head->ig = strpos;
      strpos += strlen+1;

      head->auth_type = readu32(&s);

      strlen = readu32(&s);
      readarr(&s, strpos, strlen);
      *(strpos+strlen) = 0;
      head->param = strpos;
      strpos += strlen+1;
      break;
    }

    tbuf_close(&mt);
    SYNC_ADD(&total_pages, 1);
    return page;
  }
  tbuf_close(&mt);
  return NULL;
}