Example #1
0
int mpl_read_data(MPL *mpl, char *file)
{     if (mpl->phase != 1)
         fault("mpl_read_data: invalid call sequence");
      if (file == NULL)
         fault("mpl_read_data: no input filename specified");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* process data section */
      mpl->phase = 2;
      print("Reading data section from %s...", file);
      mpl->flag_d = 1;
      open_input(mpl, file);
      /* in this case the keyword 'data' is optional */
      if (is_literal(mpl, "data"))
      {  get_token(mpl /* data */);
         if (mpl->token != T_SEMICOLON)
            error(mpl, "semicolon missing where expected");
         get_token(mpl /* ; */);
      }
      data_section(mpl);
      /* process end statement */
      end_statement(mpl);
      print("%d line%s were read", mpl->line, mpl->line == 1 ? "" : "s")
         ;
      close_input(mpl);
done: /* return to the calling program */
      return mpl->phase;
}
Example #2
0
int AudioALSA::read_buffer(char *buffer, int size)
{
//printf("AudioALSA::read_buffer 1\n");
	int attempts = 0;
	int done = 0;

	if(!get_input())
	{
		sleep(1);
		return 0;
	}

	while(attempts < 1 && !done)
	{
		if(snd_pcm_readi(get_input(), 
			buffer, 
			size / (device->in_bits / 8) / device->get_ichannels()) < 0)
		{
			printf("AudioALSA::read_buffer overrun at sample %" PRId64 "\n",
				device->total_samples_read);
//			snd_pcm_resume(get_input());
			close_input();
			open_input();
			attempts++;
		}
		else
			done = 1;
	}
	return 0;
}
Example #3
0
int main(int argc, char** argv)
{
	if(argc < 2) // insuficient arguments
		exit(1);

	if(!open_input(argv[1])) // couldn't open input file
		exit(1);

	initMe();

	yyparse();

	initSemanticAnalyzer();
	first_pass(root);
	verify(root);

	int eCount = getErrorCount();

	if(eCount > 0)
	{
		fprintf(stderr,"%d semantic errors\n", eCount);

		exit(3);
	}

	close_input();

	exit(0);
}
Example #4
0
void h2_stream_rst(h2_stream *stream, int error_code)
{
    stream->rst_error = error_code;
    close_input(stream);
    close_output(stream);
    ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, stream->session->c,
                  "h2_stream(%ld-%d): reset, error=%d", 
                  stream->session->id, stream->id, error_code);
}
Example #5
0
bool do_copy_file(compilation_env_t *env, compilation_unit_t *unit)
{
	if (!open_input(unit))
		return false;
	if (!open_output(env))
		return false;
	copy_file(env->out, unit->input);
	close_output(env);
	return close_input(unit);
}
Example #6
0
int
main(int argc, char *argv[])
{
    int c;
    bool monochrome = FALSE;
    InitPanel myInit = init_panel;
    FillPanel myFill = fill_panel;

    setlocale(LC_ALL, "");

    while ((c = getopt(argc, argv, "i:o:mwx")) != -1) {
	switch (c) {
	case 'i':
	    log_in = fopen(optarg, "r");
	    break;
	case 'o':
	    log_out = fopen(optarg, "w");
	    break;
	case 'm':
	    monochrome = TRUE;
	    break;
#if USE_WIDEC_SUPPORT
	case 'w':
	    myInit = init_wide_panel;
	    myFill = fill_wide_panel;
	    break;
#endif
	case 'x':
	    unboxed = TRUE;
	    break;
	default:
	    usage();
	}
    }
    if (unboxed)
	myFill = fill_unboxed;

    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    use_colors = monochrome ? FALSE : has_colors();
    if (use_colors)
	start_color();

    demo_panels(myInit, myFill);
    endwin();

    close_input();
    close_output();

    ExitProgram(EXIT_SUCCESS);
}
Example #7
0
void compile_file(const char *src, const char *dest){
	printf("Compiling file: %s into %s\n", src, dest);
	printf("Initializing compiler...\n");
	compile_init();
	open_input_m4(src);

	codelist_entry *entry;
	while(is_input_open()){
		while(read_input_line()){
			entry = process_line();
			if(entry != NULL){
				printf("Adding codelist entry...\n");
				add_codelist_entry(entry);
			}
		}
		close_input();
	}

	close_input();
	compile_cleanup();
}
Example #8
0
int AudioALSA::close_all()
{
	close_input();
	close_output();
	if(device->d)
	{
		snd_pcm_close(dsp_duplex);
	}
	samples_written = 0;
	delay = 0;
	interrupted = 0;
	return 1;
}
Example #9
0
apr_status_t h2_stream_schedule(h2_stream *stream, int eos,
                                h2_stream_pri_cmp *cmp, void *ctx)
{
    apr_status_t status;
    AP_DEBUG_ASSERT(stream);
    AP_DEBUG_ASSERT(stream->session);
    AP_DEBUG_ASSERT(stream->session->mplx);
    
    if (!output_open(stream)) {
        return APR_ECONNRESET;
    }
    if (stream->scheduled) {
        return APR_EINVAL;
    }
    if (eos) {
        close_input(stream);
    }
    
    /* Seeing the end-of-headers, we have everything we need to 
     * start processing it.
     */
    status = h2_request_end_headers(stream->request, stream->pool, eos);
    if (status == APR_SUCCESS) {
        if (!eos) {
            stream->bbin = apr_brigade_create(stream->pool, 
                                              stream->session->c->bucket_alloc);
        }
        stream->input_remaining = stream->request->content_length;
        
        status = h2_mplx_process(stream->session->mplx, stream->id, 
                                 stream->request, eos, cmp, ctx);
        stream->scheduled = 1;
        
        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, stream->session->c,
                      "h2_stream(%ld-%d): scheduled %s %s://%s%s",
                      stream->session->id, stream->id,
                      stream->request->method, stream->request->scheme,
                      stream->request->authority, stream->request->path);
    }
    else {
        h2_stream_rst(stream, H2_ERR_INTERNAL_ERROR);
        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, stream->session->c,
                      "h2_stream(%ld-%d): RST=2 (internal err) %s %s://%s%s",
                      stream->session->id, stream->id,
                      stream->request->method, stream->request->scheme,
                      stream->request->authority, stream->request->path);
    }
    
    return status;
}
Example #10
0
int mpl_read_model(MPL *mpl, char *file, int skip_data)
{     if (mpl->phase != 0)
         xfault("mpl_read_model: invalid call sequence\n");
      if (file == NULL)
         xfault("mpl_read_model: no input filename specified\n");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* translate model section */
      mpl->phase = 1;
      xprintf("Reading model section from %s...\n", file);
      open_input(mpl, file);
      model_section(mpl);
      if (mpl->model == NULL)
         error(mpl, "empty model section not allowed");
      /* save name of the input text file containing model section for
         error diagnostics during the generation phase */
      mpl->mod_file = xcalloc(strlen(file)+1, sizeof(char));
      strcpy(mpl->mod_file, mpl->in_file);
      /* allocate content arrays for all model objects */
      alloc_content(mpl);
      /* optional data section may begin with the keyword 'data' */
      if (is_keyword(mpl, "data"))
      {  if (skip_data)
         {  warning(mpl, "data section ignored");
            goto skip;
         }
         mpl->flag_d = 1;
         get_token(mpl /* data */);
         if (mpl->token != T_SEMICOLON)
            error(mpl, "semicolon missing where expected");
         get_token(mpl /* ; */);
         /* translate data section */
         mpl->phase = 2;
         xprintf("Reading data section from %s...\n", file);
         data_section(mpl);
      }
      /* process end statement */
      end_statement(mpl);
skip: xprintf("%d line%s were read\n",
         mpl->line, mpl->line == 1 ? "" : "s");
      close_input(mpl);
done: /* return to the calling program */
      return mpl->phase;
}
//close and clean up the video, audio, and input systems on the platform
//  returns int - negative on failure, otherwise success
int platform_close(void) {
  int result;

  result = close_video();
  if(result < 0) {
    return result;
  }

  result = close_audio();
  if(result < 0) {
    return result;
  }

  result = close_input();
  if(result < 0) {
    return result;
  }

  return 0;
}
/*****************************************************************************
  NAME: open_input

  PURPOSE:  Open all the input files and allocate associated memory for the
            filenames that reside in the data structure.

  RETURN VALUE:  Type = Input_Data_t *
      Value    Description
      -------  ---------------------------------------------------------------
      NULL     An error was encountered.
      *        A pointer to the populated Input_Data_t structure.
*****************************************************************************/
Input_Data_t *
open_input
(
    Espa_internal_meta_t *metadata, /* I: input metadata */
    bool use_toa_flag,              /* I: use TOA or SR data */
    char *dem_filename              /* I: the name of the DEM file */
)
{
    int index;
    Input_Data_t *input_data = NULL;

    input_data = (Input_Data_t *) malloc (sizeof (Input_Data_t));
    if (input_data == NULL)
    {
        ERROR_MESSAGE
            ("Error allocating memory for input data structure", MODULE_NAME);
        return NULL;
    }

    /* Initialize the band fields */
    for (index = 0; index < MAX_INPUT_BANDS; index++)
    {
        input_data->band_name[index] = NULL;
        input_data->band_fd[index] = NULL;
    }

    input_data->lines = 0;
    input_data->samples = 0;

    /* Open the input images from the XML file */
    if (GetXMLInput (metadata, use_toa_flag, dem_filename, input_data)
        != SUCCESS)
    {
        /* error messages provided by GetXMLInput */
        close_input (input_data);
        return NULL;
    }

    return input_data;
}
Example #13
0
int main(int argc, char *argv[]) {
    hs_init(&argc, &argv);
    hs_add_root(__stginit_HaskelineExport);

    // TODO: block signals at certain points of this program 
    // in order to avoid race conditions.
    hdata = initialize_input();

    signal(SIGINT, catch_signal);

    char* str1 = get_input_line(hdata,"first:");
    char* str2 = get_input_line(hdata,"second:");

    if (str1!=NULL && str2 != NULL) {
        printf("The strings were:\n%s\n%s\n",str1,str2);
    }

    close_input(hdata);

    hs_exit();
    return 0;
}
Example #14
0
apr_status_t h2_stream_close_input(h2_stream *stream)
{
    apr_status_t status = APR_SUCCESS;
    
    AP_DEBUG_ASSERT(stream);
    ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, stream->session->c,
                  "h2_stream(%ld-%d): closing input",
                  stream->session->id, stream->id);
                  
    if (stream->rst_error) {
        return APR_ECONNRESET;
    }
    
    H2_STREAM_IN(APLOG_TRACE2, stream, "close_pre");
    if (close_input(stream) && stream->bbin) {
        if (stream->request->chunked) {
            apr_table_t *trailers = stream->request->trailers;
            if (trailers && !apr_is_empty_table(trailers)) {
                status = input_add_data(stream, "0\r\n", 3, 0);
                apr_table_do(input_add_header, stream, trailers, NULL);
                status = input_add_data(stream, "\r\n", 2, 0);
            }
            else {
                status = input_add_data(stream, "0\r\n\r\n", 5, 0);
            }
        }
        
        if (status == APR_SUCCESS) {
            status = h2_stream_input_flush(stream);
        }
        if (status == APR_SUCCESS) {
            status = h2_mplx_in_close(stream->session->mplx, stream->id);
        }
    }
    H2_STREAM_IN(APLOG_TRACE2, stream, "close_post");
    return status;
}
Example #15
0
int AudioALSA::open_input()
{
	char pcm_name[BCTEXTLEN];
	snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE;
	int open_mode = 0;
	int err;

	device->in_channels = device->get_ichannels();
	device->in_bits = device->in_config->alsa_in_bits;

	translate_name(pcm_name, device->in_config->alsa_in_device);
//printf("AudioALSA::open_input %s\n", pcm_name);

	err = snd_pcm_open(&dsp_in, device->in_config->alsa_in_device, stream, open_mode);

	if(err < 0)
	{
		dsp_in = 0;
		printf("AudioALSA::open_input: %s\n", snd_strerror(err));
		return 1;
	}

	err = set_params(dsp_in, 
		device->get_ichannels(), 
		device->in_config->alsa_in_bits,
		device->in_samplerate,
		device->in_samples);
	if(err)
	{
		fprintf(stderr, "AudioALSA::open_input: set_params failed.  Aborting sampling.\n");
		close_input();
		return 1;
	}

	return 0;
}
Example #16
0
int mpl_read_data(MPL *mpl, char *file)
#if 0 /* 02/X-2008 */
{     if (mpl->phase != 1)
#else
{     if (!(mpl->phase == 1 || mpl->phase == 2))
#endif
         xfault("mpl_read_data: invalid call sequence\n");
      if (file == NULL)
         xfault("mpl_read_data: no input filename specified\n");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* process data section */
      mpl->phase = 2;
      xprintf("Reading data section from %s...\n", file);
      mpl->flag_d = 1;
      open_input(mpl, file);
      /* in this case the keyword 'data' is optional */
      if (is_literal(mpl, "data"))
      {  get_token(mpl /* data */);
         if (mpl->token != T_SEMICOLON)
            error(mpl, "semicolon missing where expected");
         get_token(mpl /* ; */);
      }
      data_section(mpl);
      /* process end statement */
      end_statement(mpl);
      xprintf("%d line%s were read\n",
         mpl->line, mpl->line == 1 ? "" : "s");
      close_input(mpl);
done: /* return to the calling program */
      return mpl->phase;
}

/*----------------------------------------------------------------------
-- mpl_generate - generate model.
--
-- *Synopsis*
--
-- #include "glpmpl.h"
-- int mpl_generate(MPL *mpl, char *file);
--
-- *Description*
--
-- The routine mpl_generate generates the model using its description
-- stored in the translator database. This phase means generating all
-- variables, constraints, and objectives, executing check and display
-- statements, which precede the solve statement (if it is presented),
-- and building the problem instance.
--
-- The character string file specifies the name of output text file, to
-- which output produced by display statements should be written. It is
-- allowed to specify NULL, in which case the output goes to stdout via
-- the routine print.
--
-- This routine should be called once after the routine mpl_read_model
-- or mpl_read_data and if one of the latters returned the code 2.
--
-- *Returns*
--
-- The routine mpl_generate returns one of the following codes:
--
-- 3 - model has been successfully generated. In this case the calling
--     program may call other api routines to obtain components of the
--     problem instance from the translator database.
-- 4 - processing failed due to some errors. In this case the calling
--     program should call the routine mpl_terminate to terminate model
--     processing. */

int mpl_generate(MPL *mpl, char *file)
{     if (!(mpl->phase == 1 || mpl->phase == 2))
         xfault("mpl_generate: invalid call sequence\n");
      /* set up error handler */
      if (setjmp(mpl->jump)) goto done;
      /* generate model */
      mpl->phase = 3;
      open_output(mpl, file);
      generate_model(mpl);
      flush_output(mpl);
      /* build problem instance */
      build_problem(mpl);
      /* generation phase has been finished */
      xprintf("Model has been successfully generated\n");
done: /* return to the calling program */
      return mpl->phase;
}

/*----------------------------------------------------------------------
-- mpl_get_prob_name - obtain problem (model) name.
--
-- *Synopsis*
--
-- #include "glpmpl.h"
-- char *mpl_get_prob_name(MPL *mpl);
--
-- *Returns*
--
-- The routine mpl_get_prob_name returns a pointer to internal buffer,
-- which contains symbolic name of the problem (model).
--
-- *Note*
--
-- Currently MathProg has no feature to assign a symbolic name to the
-- model. Therefore the routine mpl_get_prob_name tries to construct
-- such name using the name of input text file containing model section,
-- although this is not a good idea (due to portability problems). */

char *mpl_get_prob_name(MPL *mpl)
{     char *name = mpl->mpl_buf;
      char *file = mpl->mod_file;
      int k;
      if (mpl->phase != 3)
         xfault("mpl_get_prob_name: invalid call sequence\n");
      for (;;)
      {  if (strchr(file, '/') != NULL)
            file = strchr(file, '/') + 1;
         else if (strchr(file, '\\') != NULL)
            file = strchr(file, '\\') + 1;
         else if (strchr(file, ':') != NULL)
            file = strchr(file, ':') + 1;
         else
            break;
      }
      for (k = 0; ; k++)
      {  if (k == 255) break;
         if (!(isalnum((unsigned char)*file) || *file == '_')) break;
         name[k] = *file++;
      }
      if (k == 0)
         strcpy(name, "Unknown");
      else
         name[k] = '\0';
      xassert(strlen(name) <= 255);
      return name;
}
/*****************************************************************************
  NAME:  GetXMLInput

  PURPOSE:  Find the files needed by this application in the XML file and open
            them.

  RETURN VALUE:  Type = int
      Value    Description
      -------  ---------------------------------------------------------------
      SUCCESS  No errors were encountered.
      ERROR    An error was encountered.
*****************************************************************************/
int
GetXMLInput
(
    Espa_internal_meta_t *metadata, /* I: input metadata */
    bool use_toa_flag,              /* I: use TOA or SR data */
    char *dem_filename,             /* I: the name of the DEM file */
    Input_Data_t *input_data        /* O: updated with information from XML */
)
{
    int index;
    char msg[256];

    char product_name[30];
    char blue_band_name[30];
    char green_band_name[30];
    char red_band_name[30];
    char nir_band_name[30];
    char swir1_band_name[30];
    char swir2_band_name[30];

    /* Figure out the band names and product name to use */
    if ((strcmp (metadata->global.satellite, "LANDSAT_4") == 0)
        || (strcmp (metadata->global.satellite, "LANDSAT_5") == 0)
        || (strcmp (metadata->global.satellite, "LANDSAT_7") == 0))
    {
        if (use_toa_flag)
        {
            snprintf (product_name, sizeof (product_name), "toa_refl");

            snprintf (blue_band_name, sizeof (blue_band_name), "toa_band1");
            snprintf (green_band_name, sizeof (green_band_name), "toa_band2");
            snprintf (red_band_name, sizeof (red_band_name), "toa_band3");
            snprintf (nir_band_name, sizeof (nir_band_name), "toa_band4");
            snprintf (swir1_band_name, sizeof (swir1_band_name), "toa_band5");
            snprintf (swir2_band_name, sizeof (swir2_band_name), "toa_band7");
        }
        else
        {
            snprintf (product_name, sizeof (product_name), "sr_refl");

            snprintf (blue_band_name, sizeof (blue_band_name), "sr_band1");
            snprintf (green_band_name, sizeof (green_band_name), "sr_band2");
            snprintf (red_band_name, sizeof (red_band_name), "sr_band3");
            snprintf (nir_band_name, sizeof (nir_band_name), "sr_band4");
            snprintf (swir1_band_name, sizeof (swir1_band_name), "sr_band5");
            snprintf (swir2_band_name, sizeof (swir2_band_name), "sr_band7");
        }
    }
    else if (strcmp (metadata->global.satellite, "LANDSAT_8") == 0)
    {
        if (use_toa_flag)
        {
            snprintf (product_name, sizeof (product_name), "toa_refl");

            snprintf (blue_band_name, sizeof (blue_band_name), "toa_band2");
            snprintf (green_band_name, sizeof (green_band_name), "toa_band3");
            snprintf (red_band_name, sizeof (red_band_name), "toa_band4");
            snprintf (nir_band_name, sizeof (nir_band_name), "toa_band5");
            snprintf (swir1_band_name, sizeof (swir1_band_name), "toa_band6");
            snprintf (swir2_band_name, sizeof (swir2_band_name), "toa_band7");
        }
        else
        {
            snprintf (product_name, sizeof (product_name), "sr_refl");

            snprintf (blue_band_name, sizeof (blue_band_name), "sr_band2");
            snprintf (green_band_name, sizeof (green_band_name), "sr_band3");
            snprintf (red_band_name, sizeof (red_band_name), "sr_band4");
            snprintf (nir_band_name, sizeof (nir_band_name), "sr_band5");
            snprintf (swir1_band_name, sizeof (swir1_band_name), "sr_band6");
            snprintf (swir2_band_name, sizeof (swir2_band_name), "sr_band7");
        }
    }
    else
    {
        RETURN_ERROR ("Error invalid satellite", MODULE_NAME, ERROR);
    }

    /* Scan the metadata searching for the bands to open */
    for (index = 0; index < metadata->nbands; index++)
    {
        /* Only look at the ones with the product name we are looking for */
        if (strcmp (metadata->band[index].product, product_name) == 0)
        {
            if (strcmp (metadata->band[index].name, blue_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_BLUE);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              blue_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Always use this one for the lines and samples since
                   they will be the same for us, along with the pixel
                   size values */
                input_data->lines = metadata->band[index].nlines;
                input_data->samples = metadata->band[index].nsamps;
                input_data->x_pixel_size =
                    metadata->band[index].pixel_size[0];
                input_data->y_pixel_size =
                    metadata->band[index].pixel_size[1];

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_BLUE] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_BLUE] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, green_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_GREEN);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              green_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_GREEN] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_GREEN] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, red_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_RED);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              red_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_RED] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_RED] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, nir_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_NIR);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              nir_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_NIR] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_NIR] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, swir1_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_SWIR1);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              swir1_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_SWIR1] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_SWIR1] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, swir2_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_SWIR2);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              swir2_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_SWIR2] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_SWIR2] =
                    metadata->band[index].fill_value;
            }
        }

        /* Search for the CFMASK band */
        if (!strcmp (metadata->band[index].product, "cfmask"))
        {
            if (!strcmp (metadata->band[index].name, "cfmask"))
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_CFMASK);

                if (metadata->band[index].data_type != ESPA_UINT8)
                {
                    RETURN_ERROR("cfmask incompatable data type expecting"
                                 " UINT8", MODULE_NAME, ERROR);
                }

                /* Default to a no-op since CFMASK doesn't have a scale
                   factor */
                input_data->scale_factor[I_BAND_CFMASK] = 1.0;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_CFMASK] =
                    metadata->band[index].fill_value;
            }
        }
    }

    /* Add the DEM band to the list */
    open_band (dem_filename, input_data, I_BAND_DEM);
    /* Default to a no-op since DEM doesn't have a scale factor */
    input_data->scale_factor[I_BAND_DEM] = 1.0;
    /* Default so the variable is initialized
       The DEM should not have values this negative */
    input_data->fill_value[I_BAND_DEM] = -9999;

    /* Verify all the bands have something (all are required for DSWE) */
    for (index = 0; index < MAX_INPUT_BANDS; index++)
    {
        if (input_data->band_fd[index] == NULL ||
            input_data->band_name[index] == NULL)
        {
            ERROR_MESSAGE ("Error opening required input data", MODULE_NAME);

            close_input (input_data);
            return ERROR;
        }
    }

    return SUCCESS;
}
Example #18
0
static int parse_client_line(const int client_socket, char *msg)
{
  char *token;
  
  /* On récupère le premier mot, s'il est vide, on retourne direct  */
  if (!(token = strtok(msg, " ")))
    return MSG_OK;

  /*****************************************************************************
   *                              CMD_QUIT
   ****************************************************************************/
  if (!strcmp(CMD_QUIT, token))
    {
      send_ok(client_socket, DETAIL_RET_QUIT);
      return MSG_QUIT;
    }
  
  /*****************************************************************************  
   *                          CMD_CREATE_PROCESS 
   ****************************************************************************/
  else if (!strcmp(CMD_CREATE_PROCESS, token))
    {
      char *args[MAX_ARGS];
      char **pc = args;

      /* On récup le nom du prog */
      if (!(token = strtok(NULL, " ")))
	{
	  send_failure(client_socket, DETAIL_RET_CREATE_PROCESS_SYNTAX);
	  return MSG_ERR;
	}
      
      /* strtok renvoie un buffer static, on le copie */
      /* *pc = args[0] = nom du programme */
      if (!(*pc++ = strdup(token))) 
	{
	  perror("strdup");
	  return MSG_ERR;
	}
      
      /* La suite devient optionelle, c'est les arguments */
      while ((token = strtok(NULL, " ")))
	{
	  if ((*pc++ = strdup(token)) == NULL)
	    {
	      perror("strdup");
	      return MSG_ERR;
	    }
	}
      
      *pc = NULL;             /* Fin des arguments */
      
      /* On crée le processus */
      pid_t proc = create_process(args[0], args);

      /* Le processus n'a pas pu être créé */
      if (proc == -1) {
	send_failure(client_socket, DETAIL_RET_CREATE_PROCESS_ERROR);
	return MSG_ERR;
      }

      send_ok(client_socket, itoa(proc));
      return MSG_OK;
    }

  /*****************************************************************************  
   *                          CMD_DESTROY_PROCESS 
   ****************************************************************************/
  else if (!strcmp(CMD_DESTROY_PROCESS, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_DESTROY_PROCESS_SYNTAX);
	  return MSG_ERR;
	}
      
      pid_t process_to_kill = atoi(token);
      
      if (!process_exists(process_to_kill))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}
      
      destroy_process(process_to_kill);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }

  /*****************************************************************************  
   *                          CMD_SEND_INPUT      
   ****************************************************************************/
  else if (!strcmp(CMD_SEND_INPUT, token))
    {
      char buffer[MESSAGE_BUFFER_SIZE];
      buffer[0] = '\0';
      
      /* On récup le PID */
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_SEND_INPUT_SYNTAX);
	  return MSG_ERR;
	}
      
      /* Il existe ? */
      pid_t send_to_process = atoi(token);
      if (!process_exists(send_to_process))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}
      
      /* Il est déjà terminé ? */
      if (get_return_code(send_to_process) != PROCESS_NOT_TERMINATED)
	{
	  send_failure(client_socket, DETAIL_RET_PROCESS_TERMINATED);
	  return MSG_ERR;
	}

      /* Son stdin est ouvert ? */
      if (!input_open(send_to_process))
	{
	  send_failure(client_socket, DETAIL_RET_INPUT_CLOSE);
	  return MSG_ERR;
	}

      /* On récup' le message à envoyer  */
      /* TODO: Prendre la chaîne telle qu'elle, sans splitter puis merger avec un espace */
      while ((token = strtok(NULL, " ")))
	{
	  strcat(buffer, token);
	  strcat(buffer, " ");
	}
      
      /* Si le message est vide, erreur ! */
      if (strlen(buffer) == 0)
	{
	  send_failure(client_socket, DETAIL_RET_SEND_INPUT_SYNTAX);
	  return MSG_ERR;
        }
      
      /* Sinon on envoie ! */
      send_input(send_to_process, buffer);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }


  /*****************************************************************************  
   *                          CMD_CLOSE_INPUT     
   ****************************************************************************/
  else if (!strcmp(CMD_CLOSE_INPUT, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_CLOSE_INPUT_SYNTAX);
	  return MSG_ERR;
        }
      
      pid_t process_to_close_input = atoi(token);
      if (!process_exists(process_to_close_input))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}

      close_input(process_to_close_input);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }
  
  /*****************************************************************************  
   *                          CMD_GET_OUTPUT
   ****************************************************************************/
  else if (!strcmp(CMD_GET_OUTPUT, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_GET_OUTPUT_SYNTAX);
	  return MSG_ERR;
	}
      
      pid_t process_to_get_output = atoi(token);
      if (!process_exists(process_to_get_output))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
        }
     
      get_output(client_socket, process_to_get_output);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }


  /*****************************************************************************  
   *                          CMD_GET_ERROR
   ****************************************************************************/
  else if (!strcmp(CMD_GET_ERROR, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_GET_ERROR_SYNTAX);
	  return MSG_ERR;
        }
      
      pid_t process_to_get_error = atoi(token);
      if (!process_exists(process_to_get_error))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}
      
      get_error(client_socket, process_to_get_error);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }


  /*****************************************************************************  
   *                          CMD_GET_RETURN_CODE
   ****************************************************************************/
  else if (!strcmp(CMD_GET_RETURN_CODE, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_GET_RETURN_CODE_SYNTAX);
	  return MSG_ERR;
        }
      
      pid_t process_to_get_ret = atoi(token);
      if (!process_exists(process_to_get_ret))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}
      
      int ret = get_return_code(process_to_get_ret);
      if (ret == PROCESS_NOT_TERMINATED)
	{
	  send_failure(client_socket, DETAIL_RET_GET_RETURN_CODE_ERROR);
	  return MSG_ERR;
	}
      
      send_ok(client_socket, itoa(ret));
      return MSG_OK;
    }

  /*****************************************************************************  
   *                          CMD_LIST_PROCESS   
   ****************************************************************************/
  else if (!strcmp(CMD_LIST_PROCESS, token))
    {
      list_process(client_socket);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }

  /*****************************************************************************  
   *                          CMD_GET_HELP
   ****************************************************************************/
  else if (!strcmp(CMD_GET_HELP, token))
    {
      send_basic(client_socket, help, strlen(help));
      return MSG_OK;
    }

  /*****************************************************************************  
   *                        COMMANDE INCONNUE
   ****************************************************************************/
  else
    {
      send_failure(client_socket, DETAIL_RET_UNKNOWN_COMMAND);
      return MSG_UNKNOWN_COMMAND;
    }
}
Example #19
0
void close_all()
{
	close_input();
	close_output();
}
Example #20
0
// funcion main 
int main (){
       
        int x, i; 
	init_input("input"); 

// test factorial entero    
        print_string("Factorial Enteros----------------------------------");    
        x=get_int(); // lee la cantidad de veces que ejecutara la funcion  
        i = 0;        
        while (i<x){              
            int aux;         
            aux=get_int(); // lee los datos para invocar a la funcion
            aux = factorial(aux);
            print_int(aux);             
            i++;
	    }
		print_string("---------------------------------------------------------");
		
// test factorial real 
		print_string("Factorial Reales----------------------------------");
        x=get_int();  
        i = 0;
        while (i<x){
            float aux;
            aux=get_float();
            aux = factorialF(aux);
            print_float(aux); 
            i++;
	    }
		print_string("---------------------------------------------------------");

// test factorial array entero    
        print_string("Factorial Array Enteros----------------------------------");    
        x=get_int(); // lee la cantidad de veces que ejecutara la funcion  
        i = 0;        
        while (i<x){              
            int aux;         
            aux=get_int(); // lee los datos para invocar a la funcion
            aux = factorialArray(aux);
            print_int(aux);             
            i++;
	    }
		print_string("---------------------------------------------------------");

// test nthprime entero    
        print_string("Nthprime Enteros----------------------------------");    
        x=get_int(); // lee la cantidad de veces que ejecutara la funcion  
        i = 0;        
        while (i<x){              
            int aux;         
            aux=get_int(); // lee los datos para invocar a la funcion
            aux = nthprime(aux);
            print_int(aux);             
            i++;
	    }
		print_string("---------------------------------------------------------");

// test nthprime array entero    
        print_string("Nthprime Array Enteros----------------------------------");    
        x=get_int(); // lee la cantidad de veces que ejecutara la funcion  
        i = 0;        
        while (i<x){              
            int aux;         
            aux=get_int(); // lee los datos para invocar a la funcion
            aux = nthprimeArray(aux);
            print_int(aux);             
            i++;
	    }
		print_string("---------------------------------------------------------");

// test int2bin entero    
        print_string("Int2Bin Enteros----------------------------------");    
        x=get_int(); // lee la cantidad de veces que ejecutara la funcion  
        i = 0;        
        while (i<x){              
            int aux;         
            aux=get_int(); // lee los datos para invocar a la funcion
            aux = int2bin(aux);
            print_int(aux);             
            i++;
	    }
		print_string("---------------------------------------------------------");

// test gcd entero    
        print_string("GCD Enteros----------------------------------");    
        x=get_int(); // lee la cantidad de veces que ejecutara la funcion  
        i = 0;        
        while (i<x){              
            int aux;// lee los datos para invocar a la funcion
            aux = gcd(get_int(),get_int());
            print_int(aux);             
            i++;
	    }
		print_string("---------------------------------------------------------");

// test test    
        print_string("test----------------------------------");    
        test();
		print_string("---------------------------------------------------------");


// test test1    
        print_string("test1----------------------------------");    
        test1();
		print_string("---------------------------------------------------------");



        close_input();
        return 1;   
}
Example #21
0
/*
 * A command consists of one or more letter/digit pairs separated by a space.
 * Digits are limited to 1..MAX_PANELS.
 *
 * End the command with a newline.  Reject other characters.
 */
static bool
get_command(PANEL * px[MAX_PANELS + 1], char *buffer, int limit)
{
    int length = 0;
    int y0, x0;
    int c0, ch;
    WINDOW *win;

    getyx(stdscr, y0, x0);
    win = statusline();
    waddstr(win, "Command:");
    buffer[length = 0] = '\0';

    if (log_in != 0) {
	if (fgets(buffer, limit - 3, log_in) != 0) {
	    length = (int) strlen(buffer);
	    while (length > 0 && isspace(UChar(buffer[length - 1])))
		buffer[--length] = '\0';
	    waddstr(win, buffer);
	} else {
	    close_input();
	}
	(void) wgetch(win);
    } else {
	c0 = 0;
	for (;;) {
	    ch = wgetch(win);
	    if (ch == ERR || ch == QUIT || ch == ESCAPE) {
		buffer[0] = '\0';
		break;
	    } else if (ch == CTRL('L')) {
		wrefresh(curscr);
	    } else if (ch == '\n' || ch == KEY_ENTER) {
		break;
	    } else if (ch == '?') {
		show_panels(px);
	    } else if (length + 3 < limit) {
		if (ch >= KEY_MIN) {
		    beep();
		} else if (ok_letter(UChar(ch))) {
		    if (isalpha(UChar(c0))) {
			beep();
		    } else if (isdigit(UChar(c0))) {
			wprintw(win, " %c", ch);
			buffer[length++] = ' ';
			buffer[length++] = (char) (c0 = ch);
		    } else {
			wprintw(win, "%c", ch);
			buffer[length++] = (char) (c0 = ch);
		    }
		} else if (ok_digit(ch)) {
		    if (isalpha(UChar(c0))) {
			wprintw(win, "%c", ch);
			buffer[length++] = (char) (c0 = ch);
		    } else {
			beep();
		    }
		} else if (ch == ' ') {
		    if (isdigit(UChar(c0))) {
			wprintw(win, "%c", ch);
			buffer[length++] = (char) (c0 = ch);
		    } else {
			beep();
		    }
		} else {
		    beep();
		}
	    } else {
		beep();
	    }
	}
    }

    wmove(stdscr, y0, x0);

    buffer[length] = '\0';
    if (log_out && length) {
	fprintf(log_out, "%s\n", buffer);
    }
    return (length != 0);
}
Example #22
0
int
main(int argc, char *argv[])
{
	int rc;

	pesign_context *ctxp;

	int list = 0;
	int remove = 0;
	int daemon = 0;
	int fork = 1;
	int padding = 0;
	int need_db = 0;

	char *digest_name = "sha256";
	char *tokenname = "NSS Certificate DB";
	char *origtoken = tokenname;
	char *certname = NULL;
	char *certdir = "/etc/pki/pesign";
	char *signum = NULL;

	rc = pesign_context_new(&ctxp);
	if (rc < 0) {
		fprintf(stderr, "Could not initialize context: %m\n");
		exit(1);
	}

	poptContext optCon;
	struct poptOption options[] = {
		{NULL, '\0', POPT_ARG_INTL_DOMAIN, "pesign" },
		{"in", 'i', POPT_ARG_STRING, &ctxp->infile, 0,
			"specify input file", "<infile>"},
		{"out", 'o', POPT_ARG_STRING, &ctxp->outfile, 0,
			"specify output file", "<outfile>" },
		{"certficate", 'c', POPT_ARG_STRING, &certname, 0,
			"specify certificate nickname",
			"<certificate nickname>" },
		{"certdir", 'n', POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT,
			&certdir, 0,
			"specify nss certificate database directory",
			"<certificate directory path>" },
		{"force", 'f', POPT_ARG_VAL, &ctxp->force,  1,
			"force overwriting of output file", NULL },
		{"sign", 's', POPT_ARG_VAL, &ctxp->sign, 1,
			"create a new signature", NULL },
		{"hash", 'h', POPT_ARG_VAL, &ctxp->hash, 1,
			"hash binary", NULL },
		{"digest_type", 'd', POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT,
			&digest_name, 0, "digest type to use for pe hash" },
		{"import-signed-certificate", 'm',
			POPT_ARG_STRING|POPT_ARGFLAG_DOC_HIDDEN,
			&ctxp->insig, 0,"import signature from file", "<insig>" },
		{"export-signed-attributes", 'E',
			POPT_ARG_STRING|POPT_ARGFLAG_DOC_HIDDEN,
			&ctxp->outsattrs, 0, "export signed attributes to file",
			"<signed_attributes_file>" },
		{"import-signed-attributes", 'I',
			POPT_ARG_STRING|POPT_ARGFLAG_DOC_HIDDEN,
			&ctxp->insattrs, 0,
			"import signed attributes from file",
			"<signed_attributes_file>" },
		{"import-raw-signature", 'R',
			POPT_ARG_STRING|POPT_ARGFLAG_DOC_HIDDEN, &ctxp->rawsig,
			0, "import raw signature from file", "<inraw>" },
		{"signature-number", 'u', POPT_ARG_STRING, &signum, 0,
			"specify which signature to operate on","<sig-number>"},
		{"list-signatures", 'l',
			POPT_ARG_VAL|POPT_ARGFLAG_DOC_HIDDEN,
			&list, 1, "list signatures", NULL },
		{"nss-token", 't', POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT,
			&tokenname, 0, "NSS token holding signing key" },
		{"show-signature", 'S', POPT_ARG_VAL, &list, 1,
			"show signature", NULL },
		{"remove-signature", 'r', POPT_ARG_VAL, &remove, 1,
			"remove signature" },
		{"export-signature", 'e',
			POPT_ARG_STRING|POPT_ARGFLAG_DOC_HIDDEN,
			&ctxp->outsig, 0,
			"export signature to file", "<outsig>" },
		{"export-pubkey", 'K', POPT_ARG_STRING,
			&ctxp->outkey, 0, "export pubkey to file", "<outkey>" },
		{"export-cert", 'C', POPT_ARG_STRING,
			&ctxp->outcert, 0, "export signing cert to file",
			"<outcert>" },
		{"ascii-armor", 'a', POPT_ARG_VAL, &ctxp->ascii, 1,
			"use ascii armoring", NULL },
		{"daemonize", 'D', POPT_ARG_VAL, &daemon, 1,
			"run as a daemon process", NULL },
		{"nofork", 'N', POPT_ARG_VAL, &fork, 0,
			"don't fork when daemonizing", NULL },
		{"verbose", 'v', POPT_ARG_VAL, &ctxp->verbose, 1,
			"be very verbose", NULL },
		{"padding", 'P', POPT_ARG_VAL,
			&padding, 1, "pad data section", NULL },
		POPT_AUTOALIAS
		POPT_AUTOHELP
		POPT_TABLEEND
	};

	optCon = poptGetContext("pesign", argc, (const char **)argv, options,0);

	rc = poptReadDefaultConfig(optCon, 0);
	if (rc < 0 && !(rc == POPT_ERROR_ERRNO && errno == ENOENT)) {
		fprintf(stderr, "pesign: poptReadDefaultConfig failed: %s\n",
		poptStrerror(rc));
		exit(1);
	}

	while ((rc = poptGetNextOpt(optCon)) > 0)
		;

	if (rc < -1) {
		fprintf(stderr, "pesign: Invalid argument: %s: %s\n",
			poptBadOption(optCon, 0), poptStrerror(rc));
		exit(1);
	}

	if (poptPeekArg(optCon)) {
		fprintf(stderr, "pesign: Invalid Argument: \"%s\"\n",
				poptPeekArg(optCon));
		exit(1);
	}

	poptFreeContext(optCon);

	if (signum) {
		errno = 0;
		ctxp->signum = strtol(signum, NULL, 0);
		if (errno != 0) {
			fprintf(stderr, "invalid signature number: %m\n");
			exit(1);
		}
	}

	int action = 0;
	if (daemon)
		action |= DAEMONIZE;

	if (ctxp->rawsig) {
		action |= IMPORT_RAW_SIGNATURE;
		need_db = 1;
	}

	if (ctxp->insattrs)
		action |= IMPORT_SATTRS;

	if (ctxp->outsattrs)
		action |= EXPORT_SATTRS;

	if (ctxp->insig)
		action |= IMPORT_SIGNATURE;

	if (ctxp->outkey) {
		action |= EXPORT_PUBKEY;
		need_db = 1;
	}

	if (ctxp->outcert) {
		action |= EXPORT_CERT;
		need_db = 1;
	}

	if (ctxp->outsig)
		action |= EXPORT_SIGNATURE;

	if (remove != 0)
		action |= REMOVE_SIGNATURE;

	if (list != 0)
		action |= LIST_SIGNATURES;

	if (ctxp->sign) {
		action |= GENERATE_SIGNATURE;
		if (!(action & EXPORT_SIGNATURE))
			action |= IMPORT_SIGNATURE;
		need_db = 1;
	}

	if (ctxp->hash)
		action |= GENERATE_DIGEST|PRINT_DIGEST;

	if (!daemon) {
		SECStatus status;
		if (need_db)
			status = NSS_Init(certdir);
		else
			status = NSS_NoDB_Init(NULL);
		if (status != SECSuccess) {
			fprintf(stderr, "Could not initialize nss: %s\n",
				PORT_ErrorToString(PORT_GetError()));
			exit(1);
		}

		status = register_oids(ctxp->cms_ctx);
		if (status != SECSuccess) {
			fprintf(stderr, "Could not register OIDs\n");
			exit(1);
		}
	}

	rc = set_digest_parameters(ctxp->cms_ctx, digest_name);
	int is_help  = strcmp(digest_name, "help") ? 0 : 1;
	if (rc < 0) {
		if (!is_help) {
			fprintf(stderr, "Digest \"%s\" not found.\n",
				digest_name);
		}
		exit(!is_help);
	}

	ctxp->cms_ctx->tokenname = tokenname ?
		PORT_ArenaStrdup(ctxp->cms_ctx->arena, tokenname) : NULL;
	if (tokenname && !ctxp->cms_ctx->tokenname) {
		fprintf(stderr, "could not allocate token name: %s\n",
			PORT_ErrorToString(PORT_GetError()));
		exit(1);
	}
	if (tokenname != origtoken)
		free(tokenname);

	ctxp->cms_ctx->certname = certname ?
		PORT_ArenaStrdup(ctxp->cms_ctx->arena, certname) : NULL;
	if (certname && !ctxp->cms_ctx->certname) {
		fprintf(stderr, "could not allocate certificate name: %s\n",
			PORT_ErrorToString(PORT_GetError()));
		exit(1);
	}
	if (certname)
		free(certname);


	if (ctxp->sign) {
		if (!ctxp->cms_ctx->certname) {
			fprintf(stderr, "pesign: signing requested but no "
				"certificate nickname provided\n");
			exit(1);
		}
	}

	ssize_t sigspace = 0;

	switch (action) {
		case NO_FLAGS:
			fprintf(stderr, "pesign: Nothing to do.\n");
			exit(0);
			break;
		/* in this case we have the actual binary signature and the
		 * signing cert, but not the pkcs7ish certificate that goes
		 * with it.
		 */
		case IMPORT_RAW_SIGNATURE|IMPORT_SATTRS:
			check_inputs(ctxp);
			rc = find_certificate(ctxp->cms_ctx, 0);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctxp->cms_ctx->certname);
				exit(1);
			}
			open_rawsig_input(ctxp);
			open_sattr_input(ctxp);
			import_raw_signature(ctxp);
			close_sattr_input(ctxp);
			close_rawsig_input(ctxp);

			open_input(ctxp);
			open_output(ctxp);
			close_input(ctxp);
			generate_digest(ctxp->cms_ctx, ctxp->outpe, 1);
			sigspace = calculate_signature_space(ctxp->cms_ctx,
								ctxp->outpe);
			allocate_signature_space(ctxp->outpe, sigspace);
			generate_signature(ctxp->cms_ctx);
			insert_signature(ctxp->cms_ctx, ctxp->signum);
			close_output(ctxp);
			break;
		case EXPORT_SATTRS:
			open_input(ctxp);
			open_sattr_output(ctxp);
			generate_digest(ctxp->cms_ctx, ctxp->inpe, 1);
			generate_sattr_blob(ctxp);
			close_sattr_output(ctxp);
			close_input(ctxp);
			break;
		/* add a signature from a file */
		case IMPORT_SIGNATURE:
			check_inputs(ctxp);
			if (ctxp->signum > ctxp->cms_ctx->num_signatures + 1) {
				fprintf(stderr, "Invalid signature number.\n");
				exit(1);
			}
			open_input(ctxp);
			open_output(ctxp);
			close_input(ctxp);
			open_sig_input(ctxp);
			parse_signature(ctxp);
			sigspace = get_sigspace_extend_amount(ctxp->cms_ctx,
					ctxp->outpe, &ctxp->cms_ctx->newsig);
			allocate_signature_space(ctxp->outpe, sigspace);
			check_signature_space(ctxp);
			insert_signature(ctxp->cms_ctx, ctxp->signum);
			close_sig_input(ctxp);
			close_output(ctxp);
			break;
		case EXPORT_PUBKEY:
			rc = find_certificate(ctxp->cms_ctx, 1);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctxp->cms_ctx->certname);
				exit(1);
			}
			open_pubkey_output(ctxp);
			export_pubkey(ctxp);
			break;
		case EXPORT_CERT:
			rc = find_certificate(ctxp->cms_ctx, 0);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctxp->cms_ctx->certname);
				exit(1);
			}
			open_cert_output(ctxp);
			export_cert(ctxp);
			break;
		/* find a signature in the binary and save it to a file */
		case EXPORT_SIGNATURE:
			open_input(ctxp);
			open_sig_output(ctxp);
			if (ctxp->signum > ctxp->cms_ctx->num_signatures) {
				fprintf(stderr, "Invalid signature number.\n");
				exit(1);
			}
			if (ctxp->signum < 0)
				ctxp->signum = 0;
			if (ctxp->signum >= ctxp->cms_ctx->num_signatures) {
				fprintf(stderr, "No valid signature #%d.\n",
					ctxp->signum);
				exit(1);
			}
			memcpy(&ctxp->cms_ctx->newsig,
				ctxp->cms_ctx->signatures[ctxp->signum],
				sizeof (ctxp->cms_ctx->newsig));
			export_signature(ctxp->cms_ctx, ctxp->outsigfd, ctxp->ascii);
			close_input(ctxp);
			close_sig_output(ctxp);
			memset(&ctxp->cms_ctx->newsig, '\0',
				sizeof (ctxp->cms_ctx->newsig));
			break;
		/* remove a signature from the binary */
		case REMOVE_SIGNATURE:
			check_inputs(ctxp);
			open_input(ctxp);
			open_output(ctxp);
			close_input(ctxp);
			if (ctxp->signum < 0 ||
					ctxp->signum >=
					ctxp->cms_ctx->num_signatures) {
				fprintf(stderr, "Invalid signature number %d.  "
					"Must be between 0 and %d.\n",
					ctxp->signum,
					ctxp->cms_ctx->num_signatures - 1);
				exit(1);
			}
			remove_signature(ctxp);
			close_output(ctxp);
			break;
		/* list signatures in the binary */
		case LIST_SIGNATURES:
			open_input(ctxp);
			list_signatures(ctxp);
			break;
		case GENERATE_DIGEST|PRINT_DIGEST:
			open_input(ctxp);
			generate_digest(ctxp->cms_ctx, ctxp->inpe, padding);
			print_digest(ctxp);
			break;
		/* generate a signature and save it in a separate file */
		case EXPORT_SIGNATURE|GENERATE_SIGNATURE:
			rc = find_certificate(ctxp->cms_ctx, 1);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctxp->cms_ctx->certname);
				exit(1);
			}
			open_input(ctxp);
			open_sig_output(ctxp);
			generate_digest(ctxp->cms_ctx, ctxp->inpe, 1);
			generate_signature(ctxp->cms_ctx);
			export_signature(ctxp->cms_ctx, ctxp->outsigfd, ctxp->ascii);
			break;
		/* generate a signature and embed it in the binary */
		case IMPORT_SIGNATURE|GENERATE_SIGNATURE:
			check_inputs(ctxp);
			rc = find_certificate(ctxp->cms_ctx, 1);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctxp->cms_ctx->certname);
				exit(1);
			}
			if (ctxp->signum > ctxp->cms_ctx->num_signatures + 1) {
				fprintf(stderr, "Invalid signature number.\n");
				exit(1);
			}
			open_input(ctxp);
			open_output(ctxp);
			close_input(ctxp);
			generate_digest(ctxp->cms_ctx, ctxp->outpe, 1);
			sigspace = calculate_signature_space(ctxp->cms_ctx,
							     ctxp->outpe);
			allocate_signature_space(ctxp->outpe, sigspace);
			generate_digest(ctxp->cms_ctx, ctxp->outpe, 1);
			generate_signature(ctxp->cms_ctx);
			insert_signature(ctxp->cms_ctx, ctxp->signum);
			close_output(ctxp);
			break;
		case DAEMONIZE:
			rc = daemonize(ctxp->cms_ctx, certdir, fork);
			break;
		default:
			fprintf(stderr, "Incompatible flags (0x%08x): ", action);
			for (int i = 1; i < FLAG_LIST_END; i <<= 1) {
				if (action & i)
					print_flag_name(stderr, i);
			}
			fprintf(stderr, "\n");
			exit(1);
	}
	pesign_context_free(ctxp);

	if (!daemon) {
		SECStatus status = NSS_Shutdown();
		if (status != SECSuccess) {
			fprintf(stderr, "could not shut down NSS: %s",
				PORT_ErrorToString(PORT_GetError()));
			exit(1);
		}
	}

	return (rc < 0);
}
Example #23
0
int
main(int argc, char *argv[])
{
	int rc;

	pesign_context ctx, *ctxp = &ctx;

	int list = 0;
	int remove = 0;

	char *digest_name = "sha256";

	poptContext optCon;
	struct poptOption options[] = {
		{NULL, '\0', POPT_ARG_INTL_DOMAIN, "pesign" },
		{"in", 'i', POPT_ARG_STRING, &ctx.infile, 0,
			"specify input file", "<infile>"},
		{"out", 'o', POPT_ARG_STRING, &ctx.outfile, 0,
			"specify output file", "<outfile>" },
		{"certficate", 'c', POPT_ARG_STRING, &ctx.cms_ctx.certname, 0,
			"specify certificate nickname",
			"<certificate nickname>" },
		{"privkey", 'p', POPT_ARG_STRING, &ctx.privkeyfile, 0,
			"specify private key file", "<privkey>" },
		{"force", 'f', POPT_ARG_VAL, &ctx.force,  1,
			"force overwriting of output file", NULL },
		{"nogaps", 'n',
			POPT_ARG_VAL|POPT_ARGFLAG_DOC_HIDDEN,
			&ctx.hashgaps, 0,
			"skip gaps between sections when signing", NULL },
		{"sign", 's', POPT_ARG_VAL, &ctx.sign, 1,
			"create a new signature", NULL },
		{"hash", 'h', POPT_ARG_VAL, &ctx.hash, 1, "hash binary", NULL },
		{"digest_type", 'd', POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT,
			&digest_name, 0, "digest type to use for pe hash" },
		{"import-signature", 'm',
			POPT_ARG_STRING|POPT_ARGFLAG_DOC_HIDDEN,
			&ctx.insig, 0,"import signature from file", "<insig>" },
		{"signature-number", 'u', POPT_ARG_INT, &ctx.signum, -1,
			"specify which signature to operate on","<sig-number>"},
		{"list-signatures", 'l',
			POPT_ARG_VAL|POPT_ARGFLAG_DOC_HIDDEN,
			&list, 1, "list signatures", NULL },
		{"show-signature", 'S', POPT_ARG_VAL, &list, 1,
			"show signature", NULL },
		{"remove-signature", 'r', POPT_ARG_VAL, &remove, 1,
			"remove signature" },
		{"export-signature", 'e',
			POPT_ARG_STRING|POPT_ARGFLAG_DOC_HIDDEN,
			&ctx.outsig, 0,"export signature to file", "<outsig>" },
		{"export-pubkey", 'K', POPT_ARG_STRING,
			&ctx.outkey, 0, "export pubkey to file", "<outkey>" },
		{"export-cert", 'C', POPT_ARG_STRING,
			&ctx.outcert, 0, "export signing cert to file",
			"<outcert>" },
		{"ascii-armor", 'a', POPT_ARG_VAL, &ctx.ascii, 1,
			"use ascii armoring", NULL },
		POPT_AUTOALIAS
		POPT_AUTOHELP
		POPT_TABLEEND
	};

	rc = pesign_context_init(ctxp);
	if (rc < 0) {
		fprintf(stderr, "Could not initialize context: %m\n");
		exit(1);
	}

	optCon = poptGetContext("pesign", argc, (const char **)argv, options,0);

	while ((rc = poptGetNextOpt(optCon)) > 0)
		;

	if (rc < -1) {
		fprintf(stderr, "pesign: Invalid argument: %s: %s\n",
			poptBadOption(optCon, 0), poptStrerror(rc));
		exit(1);
	}

	if (poptPeekArg(optCon)) {
		fprintf(stderr, "pesign: Invalid Argument: \"%s\"\n",
				poptPeekArg(optCon));
		exit(1);
	}

	poptFreeContext(optCon);

	rc = set_digest_parameters(&ctx.cms_ctx, digest_name);
	int is_help  = strcmp(digest_name, "help") ? 0 : 1;
	if (rc < 0) {
		if (!is_help) {
			fprintf(stderr, "Digest \"%s\" not found.\n",
				digest_name);
		}
		exit(!is_help);
	}

	int action = 0;
	if (ctx.insig)
		action |= IMPORT_SIGNATURE;

	if (ctx.outkey)
		action |= EXPORT_PUBKEY;

	if (ctx.outcert)
		action |= EXPORT_CERT;

	if (ctx.outsig)
		action |= EXPORT_SIGNATURE;

	if (remove != 0)
		action |= REMOVE_SIGNATURE;

	if (list != 0)
		action |= LIST_SIGNATURES;

	if (ctx.sign) {
		action |= GENERATE_SIGNATURE;
		if (!(action & EXPORT_SIGNATURE))
			action |= IMPORT_SIGNATURE;
	}

	if (ctx.hash)
		action |= GENERATE_DIGEST|PRINT_DIGEST;

	SECItem newsig;

	switch (action) {
		case NO_FLAGS:
			fprintf(stderr, "pesign: Nothing to do.\n");
			exit(0);
			break;
		/* add a signature from a file */
		case IMPORT_SIGNATURE:
			check_inputs(ctxp);
			open_input(ctxp);
			open_output(ctxp);
			close_input(ctxp);
			open_sig_input(ctxp);
			import_signature(ctxp);
			close_sig_input(ctxp);
			close_output(ctxp);
			break;
		case EXPORT_PUBKEY:
			rc = find_certificate(&ctx.cms_ctx);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctx.cms_ctx.certname);
				exit(1);
			}
			open_pubkey_output(ctxp);
			export_pubkey(ctxp);
			break;
		case EXPORT_CERT:
			rc = find_certificate(&ctx.cms_ctx);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctx.cms_ctx.certname);
				exit(1);
			}
			open_cert_output(ctxp);
			export_cert(ctxp);
			break;
		/* find a signature in the binary and save it to a file */
		case EXPORT_SIGNATURE:
			open_input(ctxp);
			open_sig_output(ctxp);
			if (ctx.signum > ctx.cms_ctx.num_signatures) {
				fprintf(stderr, "Invalid signature number.\n");
				exit(1);
			}
			SECItem *sig = ctx.cms_ctx.signatures[ctx.signum];
			export_signature(ctxp, sig);
			close_input(ctxp);
			close_sig_output(ctxp);
			break;
		/* remove a signature from the binary */
		case REMOVE_SIGNATURE:
			check_inputs(ctxp);
			open_input(ctxp);
			open_output(ctxp);
			close_input(ctxp);
			if (ctx.signum > ctx.cms_ctx.num_signatures) {
				fprintf(stderr, "Invalid signature number.\n");
				exit(1);
			}
			remove_signature(&ctx);
			close_output(ctxp);
			break;
		/* list signatures in the binary */
		case LIST_SIGNATURES:
			open_input(ctxp);
			list_signatures(ctxp);
			break;
		case GENERATE_DIGEST|PRINT_DIGEST:
			open_input(ctxp);
			generate_digest(ctxp, ctx.inpe);
			print_digest(ctxp);
			break;
		/* generate a signature and save it in a separate file */
		case EXPORT_SIGNATURE|GENERATE_SIGNATURE:
			rc = find_certificate(&ctx.cms_ctx);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctx.cms_ctx.certname);
				exit(1);
			}
			open_input(ctxp);
			open_sig_output(ctxp);
			generate_digest(ctxp, ctx.inpe);
			generate_signature(ctxp, &newsig);
			export_signature(ctxp, &newsig);
			break;
		/* generate a signature and embed it in the binary */
		case IMPORT_SIGNATURE|GENERATE_SIGNATURE:
			check_inputs(ctxp);
			rc = find_certificate(&ctx.cms_ctx);
			if (rc < 0) {
				fprintf(stderr, "pesign: Could not find "
					"certificate %s\n",
					ctx.cms_ctx.certname);
				exit(1);
			}
			open_input(ctxp);
			open_output(ctxp);
			close_input(ctxp);
			generate_digest(ctxp, ctx.outpe);
			generate_signature(ctxp, &newsig);
			insert_signature(ctxp, &newsig);
			close_output(ctxp);
			break;
		default:
			fprintf(stderr, "Incompatible flags (0x%08x): ", action);
			for (int i = 1; i < FLAG_LIST_END; i <<= 1) {
				if (action & i)
					print_flag_name(stderr, i);
			}
			fprintf(stderr, "\n");
			exit(1);
	}
	pesign_context_fini(&ctx);
	return (rc < 0);
}
Example #24
0
/******************************************************************************
MODULE:  open_input

PURPOSE:  Sets up the input data structure, opens the input TOA file for
read access, opens the input brightness temp file for read access, allocates
space, and stores some of the metadata for later reference.

RETURN VALUE:
Type = Input_t*
Value      Description
-----      -----------
NULL       Error occurred opening or reading the files
non-NULL   Successful completion
 

PROJECT:  Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS

HISTORY:
Date        Programmer       Reason
--------    ---------------  -------------------------------------
1/2/2012    Gail Schmidt     Original Development (based on input routines
                             from the LEDAPS lndsr application)

NOTES:
  1. This routine opens the input TOA reflectance and brightness temperature
     files and associated SDSs.  It also allocates memory for pointers in the
     input structure.  It is up to the caller to use close_input and
     free_input to close the HDF files and free up the memory when done
     using the input data structure.
******************************************************************************/
Input_t *open_input
(
    char *refl_file_name,     /* I: input TOA reflectance filename */
    char *btemp_file_name     /* I: input brightness temp filename */
)
{
    char FUNC_NAME[] = "open_input";   /* function name */
    char errmsg[STR_SIZE];    /* error message */
    char sds_name[STR_SIZE];  /* name of the current SDS */
    int ib;                   /* index for bands */
    int ir;                   /* index for dimension rank */
    double dval[10];          /* double value for reading the attributes for
                                 the current band like fill, saturation
                                 value, and scale factor */
    Myhdf_dim_t *dim[2];      /* dimensions for the current SDS */
    Input_t *this = NULL;     /* input data structure to be initialized,
                                 populated, and returned to the caller */
    Myhdf_attr_t attr;        /* values for the SDS attributes */
    int16 *buf = NULL;        /* temporary buffer to allocate memory for
                                 the TOA reflectance bands */
  
    /* Create the Input data structure */
    this = (Input_t *) malloc (sizeof (Input_t));
    if (this == NULL) 
    {
        strcpy (errmsg, "Error allocating memory for Input data structure");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
  
    /* Populate the filenames in the data structure */
    this->refl_file_name = dup_string (refl_file_name);
    if (this->refl_file_name == NULL)
    {
        free (this);
        strcpy (errmsg, "Error duplicating the TOA reflectance filename");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }

    this->btemp_file_name = dup_string (btemp_file_name);
    if (this->btemp_file_name == NULL)
    {
        free (this);
        strcpy (errmsg, "Error duplicating the brightness temp filename");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
  
    /* Open the files for SD access */
    this->refl_sds_file_id = SDstart ((char *)refl_file_name, DFACC_RDONLY);
    if (this->refl_sds_file_id == HDF_ERROR)
    {
        free (this->refl_file_name);
        free (this);  
        sprintf (errmsg, "Error opening the input TOA reflectance file: %s",
            refl_file_name);
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    this->refl_open = true;
  
    this->btemp_sds_file_id = SDstart ((char *)btemp_file_name, DFACC_RDONLY);
    if (this->btemp_sds_file_id == HDF_ERROR)
    {
        free (this->refl_file_name);
        free (this->btemp_file_name);
        free (this);  
        sprintf (errmsg, "Error opening the input brightness temperature "
            "file: %s", btemp_file_name);
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    this->btemp_open = true;
  
    /* Get the global metadata from the input TOA reflectance file */
    if (get_input_meta (this) != SUCCESS)
    {
        free (this->refl_file_name);
        free (this->btemp_file_name);
        free (this);  
        sprintf (errmsg, "Error reading the input metadata from file: %s",
            refl_file_name);
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
  
    /* Get SDS information and start SDS access */
    for (ib = 0; ib < this->nrefl_band; ib++)
    {
        this->refl_sds[ib].name = NULL;
        this->refl_sds[ib].dim[0].name = NULL;
        this->refl_sds[ib].dim[1].name = NULL;
        this->refl_buf[ib] = NULL;
    }
  
    this->btemp_sds.name = NULL;
    this->btemp_sds.dim[0].name = NULL;
    this->btemp_sds.dim[1].name = NULL;
    this->btemp_buf = NULL;
  
    /* Loop through the image bands and obtain the SDS information */
    strcpy (errmsg, "none");
    for (ib = 0; ib < this->nrefl_band; ib++)
    {
        /* Get the SDS name and information */
        sprintf (sds_name, "%s%d", SDS_PREFIX, this->meta.refl_band[ib]);
        this->refl_sds[ib].name = dup_string (sds_name);
        if (this->refl_sds[ib].name == NULL)
        {
            sprintf (errmsg, "Error getting the SDS name for TOA reflectance "
                "band %d", ib);
            break;
        }
    
        if (get_sds_info (this->refl_sds_file_id, &this->refl_sds[ib])
            != SUCCESS)
        {
            sprintf (errmsg, "Error getting the SDS info for TOA reflectance "
                "band %d", ib);
            break;
        }
    
        /* Check rank */
        if (this->refl_sds[ib].rank != 2)
        {
            sprintf (errmsg, "Invalid rank for the SDS for TOA reflectance "
                "band %d", ib);
            break;
        }
    
        /* Check SDS type */
        if (this->refl_sds[ib].type != DFNT_INT16)
        {
            sprintf (errmsg, "Invalid data type for the SDS for TOA "
                "reflectance band %d.  Should be INT16.", ib);
            break;
        }
    
        /* Get dimensions */
        for (ir = 0; ir < this->refl_sds[ib].rank; ir++)
        {
            dim[ir] = &this->refl_sds[ib].dim[ir];
            if (get_sds_dim_info (this->refl_sds[ib].id, ir, dim[ir])
                != SUCCESS)
            {
                sprintf (errmsg, "Error obtaining the dimensions of the SDS "
                    "for TOA reflectance band %d.", ib);
                break;
            }
        }
    
        /* Save and check line and sample dimensions */
        if (ib == 0)
        {
            this->nlines = dim[0]->nval;
            this->nsamps = dim[1]->nval;
        }
        else
        {
            if (this->nlines != dim[0]->nval)
            {
                sprintf (errmsg, "Dimensions for the number of lines in TOA "
                    "reflectance band %d does not match the previous "
                    "dimensions for band 0.", ib);
                break;
            }
            if (this->nsamps != dim[1]->nval)
            {
                sprintf (errmsg, "Dimensions for the number of samples in TOA "
                    "reflectance band %d does not match the previous "
                    "dimensions for band 0.", ib);
                break;
            }
        }
    
        /* If this is the first image band read the attribute metadata */
        if (ib == 0)
        {
            /* Fill value */
            attr.type = DFNT_INT16;
            attr.nval = 1;
            attr.name = INPUT_FILL_VALUE;
            if (get_attr_double (this->refl_sds[ib].id, &attr, dval) != SUCCESS)
            {
                sprintf (errmsg, "Error reading the fill value SDS attribute "
                    "for reflectance band %d.", ib);
                break;
            }
            if (attr.nval != 1) 
            {
                sprintf (errmsg, "Invalid number of values for the fill value "
                    "for reflectance band %d.", ib);
                break;
            }
            this->refl_fill = (int) dval[0];

            /* Scale factor */
            attr.type = DFNT_FLOAT32;
            attr.nval = 1;
            attr.name = INPUT_SCALE_FACTOR;
            if (get_attr_double (this->refl_sds[ib].id, &attr, dval) != SUCCESS)
            {
                sprintf (errmsg, "Error reading the scale factor SDS "
                    "attribute for reflectance band %d.", ib);
                break;
            }
            if (attr.nval != 1) 
            {
                sprintf (errmsg, "Invalid number of values for the scale "
                    "factor for reflectance band %d.", ib);
                break;
            }
            this->refl_scale_fact = dval[0];

            /* Saturation value */
            attr.type = DFNT_INT16;
            attr.nval = 1;
            attr.name = INPUT_SATURATE_VALUE;
            if (get_attr_double (this->refl_sds[ib].id, &attr, dval) != SUCCESS)
            {
                sprintf (errmsg, "Error reading the saturation value SDS "
                    "attribute for reflectance band %d.", ib);
                break;
            }
            if (attr.nval != 1) 
            {
                sprintf (errmsg, "Invalid number of values for the saturation "
                    "value for reflectance band %d.", ib);
                break;
            }
            this->refl_saturate_val = (int) dval[0];
        }  /* end if first band */
    }  /* for ib */
  
    /* Check for any errors processing the reflectance bands and use the
       error message already created */
    if (strcmp (errmsg, "none"))
    {
        close_input (this);
        free_input (this);
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }

    /* For the single thermal band, obtain the SDS information */
    strcpy (sds_name, "band6");
    this->btemp_sds.name = dup_string (sds_name);
    if (this->btemp_sds.name == NULL)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Error getting the brightness temperature SDS name");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    
    if (get_sds_info (this->btemp_sds_file_id, &this->btemp_sds) != SUCCESS)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Error getting the SDS info for the brightness "
            "temperature band");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    
    /* Check rank */
    if (this->btemp_sds.rank != 2)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Invalid rank for the brightness temp SDS");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    
    /* Check SDS type */
    if (this->btemp_sds.type != DFNT_INT16)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Invalid data type for the brightness temp SDS.  "
            "Should be INT16.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    
    /* Get dimensions */
    for (ir = 0; ir < this->btemp_sds.rank; ir++)
    {
        dim[ir] = &this->btemp_sds.dim[ir];
        if (get_sds_dim_info (this->btemp_sds.id, ir, dim[ir]))
        {
            close_input (this);
            free_input (this);
            sprintf (errmsg, "Error obtaining the dimensions of the SDS "
                "for brightness temperature.");
            error_handler (true, FUNC_NAME, errmsg);
            return (NULL);
        }
    }
    
    /* Check line and sample dimensions with the reflectance dimensions */
    if (this->nlines != dim[0]->nval)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Dimensions for the number of lines in the "
            "brightness temp band does not match the dimensions for the "
            "reflectance TOA bands.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    if (this->nsamps != dim[1]->nval)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Dimensions for the number of samples in the "
            "brightness temp band does not match the dimensions for the "
            "reflectance TOA bands.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    
    /* Read the attribute metadata */
    /* Fill value */
    attr.type = DFNT_INT16;
    attr.nval = 1;
    attr.name = INPUT_FILL_VALUE;
    if (get_attr_double (this->btemp_sds.id, &attr, dval) != SUCCESS)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Error reading the fill value SDS attribute "
            "for the brightness temperature band.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    if (attr.nval != 1) 
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Invalid number of values for the fill value "
            "for the brightness temperature band.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    this->btemp_fill = (int) dval[0];

    /* Scale factor */
    attr.type = DFNT_FLOAT32;
    attr.nval = 1;
    attr.name = INPUT_SCALE_FACTOR;
    if (get_attr_double (this->btemp_sds.id, &attr, dval) != SUCCESS)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Error reading the scale factor SDS "
            "attribute for the brightness temperature band.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    if (attr.nval != 1) 
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Invalid number of values for the scale "
            "factor for the brightness temperature band.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    this->btemp_scale_fact = dval[0];

    /* Saturation value */
    attr.type = DFNT_FLOAT32;
    attr.nval = 1;
    attr.name = INPUT_SATURATE_VALUE;
    if (get_attr_double (this->btemp_sds.id, &attr, dval) != SUCCESS)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Error reading the saturation value SDS "
            "attribute for the brightness temperature band.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    if (attr.nval != 1) 
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Invalid number of values for the saturation "
            "value for the brightness temperature band.");
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    this->btemp_saturate_val = (int) dval[0];

    /* Allocate input buffers.  TOA reflectance buffer has multiple bands.
       Thermal band has one band.  Allocate PROC_NLINES of data for each
       band. */
    buf = (int16 *) calloc (PROC_NLINES * this->nsamps * this->nrefl_band,
        sizeof (int16));
    if (buf == NULL)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Error allocating memory for input TOA reflectance "
            "buffer containing %d lines.", PROC_NLINES);
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
    else
    {
        /* Set up the memory buffers for each band */
        this->refl_buf[0] = buf;
        for (ib = 1; ib < this->nrefl_band; ib++)
            this->refl_buf[ib] = this->refl_buf[ib-1] +
                PROC_NLINES * this->nsamps;
    }
  
    this->btemp_buf = (int16 *) calloc (PROC_NLINES * this->nsamps,
        sizeof (int16));
    if (this->btemp_buf == NULL)
    {
        close_input (this);
        free_input (this);
        sprintf (errmsg, "Error allocating memory for input brightness temp "
            "buffer containing %d lines.", PROC_NLINES);
        error_handler (true, FUNC_NAME, errmsg);
        return (NULL);
    }
  
    return (this);
}
Example #25
0
int main(int narg,char **arg)
{
  char filename[1024];

  //basic mpi initialization
  init_nissa();

  if(narg<2 && rank==0)
    {
      fprintf(stderr,"Use: %s input_file\n",arg[0]);
      fflush(stderr);
      MPI_Abort(MPI_COMM_WORLD,1);
    }

  open_input(arg[1]);

  int L,T;
  read_str_int("L",&L);
  read_str_int("T",&T);
  read_str_str("Filename",filename,1024);

  close_input();

  //Init the MPI grid 
  init_grid(T,L);

  ///////////////////////////////////////////

  quad_su3 *conf=(quad_su3*)malloc(sizeof(quad_su3)*(loc_vol));
  read_ildg_gauge_conf(conf,filename);

  su3 *Pl=(su3*)malloc(sizeof(su3)*(loc_vol));
  //Pline_serial_forward(Pl, conf);
  //Pline_forward(Pl, conf);
  //Pline_serial(Pl, conf);
  //Pline(Pl, conf);
  //Pline_serial_backward(Pl,conf);
  Pline_backward(Pl,conf);
  
  int ic_in, ic_out; //auxiliar color indices

  for (int rank_x0=0; rank_x0<nrank_dir[0]; rank_x0++) for (int rank_x1=0; rank_x1<nrank_dir[1]; rank_x1++) for (int rank_x2=0; rank_x2<nrank_dir[2]; rank_x2++) for (int rank_x3=0; rank_x3<nrank_dir[3]; rank_x3++){
    if(rank_coord[0]==rank_x0 && rank_coord[1]==rank_x1 && rank_coord[2]==rank_x2 && rank_coord[3]==rank_x3){
  //for (int irank=0; irank<nissa_nranks ; irank++){ if(rank==irank){
	for(int ivol=0;ivol<loc_vol;ivol++){
  	printf("(t,x,y,z)=(%d,%d,%d,%d)\n",glb_coord_of_loclx[ivol][0],glb_coord_of_loclx[ivol][1],glb_coord_of_loclx[ivol][2],glb_coord_of_loclx[loc_site][3]);
	  for (ic_in=0; ic_in<3; ic_in++){
		printf("[");
		for(ic_out=0; ic_out<3; ic_out++) printf("%8.8f +I %8.8f \t",Pl[ivol][ic_in][ic_out][0],Pl[ivol][ic_in][ic_out][1]);
		printf("]\n");
           }
         }
	}
        MPI_Barrier(MPI_COMM_WORLD);
   }




  free(conf);
  free(Pl);
  
  ///////////////////////////////////////////

  close_nissa();

  return 0;
}
int main( int argc, char **argv ) {

	char *filename;
	struct INPUT *input;
	int x1, y1;
	int x2, y2;
	int TopX, TopY;
	int BottomX, BottomY;

	if( argc != 2 ) {
		fprintf( stderr, "usage: %s event-device - probably /dev/input/event0\n", argv[0] );
		exit( 1 );
	}

	filename = argv[1];

	input = open_input( filename );

	fprintf(
		stderr,
		"\nPlease, press the stilus at ANY\n"
		"corner of your desired working area: "
	);
	capture_key( input, &x1, &y1, NUM_REGISTER_KEYS, register_keys );
	fprintf( stderr, "ok, got %d,%d\n", x1, y1 );

	fprintf(
		stderr,
		"\nPlease, press the stilus at OPPOSITE\n"
		"corner of your desired working area: "
	);
	capture_key( input, &x2, &y2, NUM_REGISTER_KEYS, register_keys );
	fprintf( stderr, "ok, got %d,%d\n", x2, y2 );

	if( x2 > x1 ) {
		TopX = x1;
		BottomX = x2;
	} else {
		TopX = x2;
		BottomX = x1;
	}

	if( y2 > y1 ) {
		TopY = y1;
		BottomY = y2;
	} else {
		TopY = y2;
		BottomY = y1;
	}

	fprintf(
		stderr,
		"\nAccording to your input you may put following\n"
		"lines into your XF86Config file:\n"
		"\n"
	);
	printf(
		"\tDriver\t\t\"wizardpen\"\n"
		"\tOption\t\t\"Device\"\t\"%s\"\n"
		"\tOption\t\t\"TopX\"\t\t\"%d\"\n"
		"\tOption\t\t\"TopY\"\t\t\"%d\"\n"
		"\tOption\t\t\"BottomX\"\t\"%d\"\n"
		"\tOption\t\t\"BottomY\"\t\"%d\"\n"
		"\tOption\t\t\"MaxX\"\t\t\"%d\"\n"
		"\tOption\t\t\"MaxY\"\t\t\"%d\"\n",
		filename,
		TopX, TopY,
		BottomX, BottomY,
		BottomX, BottomY
	);

	close_input( input );
	exit( 0 );
}