Exemplo n.º 1
0
myAudioStream::myAudioStream(QString payload)
{
    if (!initialized) {
        ortp_set_log_level_mask(ORTP_DEBUG|ORTP_ERROR);
        ms_init();
        ortp_init();
        initialized = true;
    }

    if (!init_card()) {
        return;
    }
    if (!init_stream()) {
        return;
    }
    if (!init_filters(payload)) {
        return;
    }
    if (!link_filters()) {
        return;
    }
    if (!start_ticker()) {
        return;
    }
}
Exemplo n.º 2
0
/*!*****************************************************************************
 *******************************************************************************
\note  filt
\date  Feb 1999
   
\remarks 

    applies a 2nd order butteworth filter

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

 \param[in]     raw : the raw data
 \param[in]     fptr: pointer to the filter data structure 

     returns the filtered value

 ******************************************************************************/
double
filt(double raw, Filter *fptr)

{

  int i,j;

  if (!filters_initialized)
    init_filters();

  fptr->raw[0]  = raw;

  if (fptr->cutoff == 100) {

    fptr->filt[0] = raw;

  } else {

    fptr->filt[0] = 
      filters_b[fptr->cutoff][0] * fptr->raw[0] +
      filters_b[fptr->cutoff][1] * fptr->raw[1] + 
      filters_b[fptr->cutoff][2] * fptr->raw[2] -
      filters_a[fptr->cutoff][1] * fptr->filt[1] -
      filters_a[fptr->cutoff][2] * fptr->filt[2];
    
  }

  fptr->raw[2]  = fptr->raw[1];
  fptr->raw[1]  = fptr->raw[0];
  fptr->filt[2] = fptr->filt[1];
  fptr->filt[1] = fptr->filt[0];

  return fptr->filt[0];

}
Exemplo n.º 3
0
int motor_init(void)
{
	_watchdog_id = watchdog_create(WATCHDOG_TIMEOUT_MSEC);
	if (_watchdog_id < 0) {
		return _watchdog_id;
	}

	int ret = motor_rtctl_init();
	if (ret) {
		return ret;
	}

	chMtxInit(&_mutex);
	chEvtInit(&_setpoint_update_event);

	configure();

	init_filters();
	if (_state.input_voltage < MIN_VALID_INPUT_VOLTAGE || _state.input_voltage > MAX_VALID_INPUT_VOLTAGE) {
		lowsyslog("Motor: Invalid input voltage: %f\n", _state.input_voltage);
		return -1;
	}

	ret = rpmctl_init();
	if (ret) {
		return ret;
	}

	motor_rtctl_stop();

	assert_always(chThdCreateStatic(_wa_control_thread, sizeof(_wa_control_thread),
	                                HIGHPRIO, control_thread, NULL));
	return 0;
}
Exemplo n.º 4
0
int
main (int argc, gchar *argv[])
{
  gchar *interface = NULL;
  gchar *type = NULL;

  GOptionEntry entries[] = {
    { "configure",      'c', 0, G_OPTION_ARG_STRING, &interface, N_("Configure a network interface"), N_("INTERFACE") },
    { "configure-type", 't', 0, G_OPTION_ARG_STRING, &type,      N_("Configure the first network interface with a specific type"), N_("TYPE") },
    { NULL }
  };

  #if !GLIB_CHECK_VERSION (2, 32, 0)
    g_thread_init (NULL);
  #endif

  gst_init_tool ("network-admin", argc, argv, entries);
  tool = gst_network_tool_new ();

  gst_dialog_require_authentication_for_widgets (tool->main_dialog, policy_widgets);
  gst_dialog_connect_signals (tool->main_dialog, signals);
  gst_dialog_connect_signals_after (tool->main_dialog, signals_after);
  set_text_buffers_callback ();
  init_filters ();

  if (interface)
    init_standalone_dialog (tool, SEARCH_DEV, interface);
  else if (type)
    init_standalone_dialog (tool, SEARCH_TYPE, type);
  else
    gtk_widget_show (GTK_WIDGET (tool->main_dialog));

  gtk_main ();
  return 0;
}
Exemplo n.º 5
0
/*!*****************************************************************************
 *******************************************************************************
\note  init_vision_processing
\date  June 1999
   
\remarks 

          initialization for vision processing

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

     none

 ******************************************************************************/
int
init_vision_processing(void)

{
  
  int i,j;
  static int firsttime = TRUE;

  stereo_mode = VISION_3D_MODE;
  
  if (firsttime) {
    firsttime = FALSE;
    blobpp = (BlobPP *) my_calloc(max_blobs+1,sizeof(BlobPP),MY_STOP);
  }

#if 1
  /* initialize matrices */
  if (!init_matrices())
      return FALSE;
#endif

  /* initialize filtering */
  if (!init_filters())
    return FALSE;
  
  /* initialize post processing */
  if (!init_pp((char *)vision_default_pp))
    return FALSE;
  
  return TRUE;
  
}
Exemplo n.º 6
0
/*!*****************************************************************************
 *******************************************************************************
\note  add_goto_cart_task
\date  Feb 1999
\remarks 

adds the task to the task menu

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

none

 ******************************************************************************/
void
add_goto_cart_task( void )

{
  int i, j;
  static int firsttime = TRUE;
  
  if (firsttime) {
    firsttime = FALSE;

    cart    = my_vector(1,n_endeffs*6);
    ctarget = (SL_Cstate *) my_calloc(n_endeffs+1,sizeof(SL_Cstate),MY_STOP);
    cnext   = (SL_Cstate *) my_calloc(n_endeffs+1,sizeof(SL_Cstate),MY_STOP);
    cstatus = my_ivector(1,n_endeffs*6);
    target  = (SL_DJstate *)my_calloc(n_dofs+1,sizeof(SL_DJstate),MY_STOP);
    fthdd   = (Filter *)my_calloc(n_dofs+1,sizeof(Filter),MY_STOP);
    target  = (SL_DJstate *)my_calloc(n_dofs+1,sizeof(SL_DJstate),MY_STOP);

    // initialize the filters
    init_filters();
    for (i=1; i<=n_dofs; ++i) 
      fthdd[i].cutoff = 5;
    
    addTask("Goto Cart Task", init_goto_cart_task, 
	    run_goto_cart_task, change_goto_cart_task);
    addToMan("goVisTarget","move one endeff to blob1",goVisTarget);
    
  }

}    
Exemplo n.º 7
0
PyMODINIT_FUNC
_PyWarnings_Init(void)
{
    PyObject *m;

    m = Py_InitModule3(MODULE_NAME, warnings_functions, warnings__doc__);
    if (m == NULL)
        return;

    _filters = init_filters();
    if (_filters == NULL)
        return;
    Py_INCREF(_filters);
    if (PyModule_AddObject(m, "filters", _filters) < 0)
        return;

    _once_registry = PyDict_New();
    if (_once_registry == NULL)
        return;
    Py_INCREF(_once_registry);
    if (PyModule_AddObject(m, "once_registry", _once_registry) < 0)
        return;

    _default_action = PyString_FromString("default");
    if (_default_action == NULL)
        return;
    if (PyModule_AddObject(m, "default_action", _default_action) < 0)
        return;
}
Exemplo n.º 8
0
Arquivo: motor.c Projeto: branux/sapog
int motor_init(void)
{
	_watchdog_id = watchdogCreate(WATCHDOG_TIMEOUT_MSEC);
	if (_watchdog_id < 0) {
		return _watchdog_id;
	}

	int ret = motor_rtctl_init();
	if (ret) {
		return ret;
	}

	configure();

	init_filters();
	if (_state.input_voltage < MIN_VALID_INPUT_VOLTAGE || _state.input_voltage > MAX_VALID_INPUT_VOLTAGE) {
		printf("Motor: Invalid input voltage: %f\n", _state.input_voltage);
		return -1;
	}

	ret = rpmctl_init();
	if (ret) {
		return ret;
	}

	motor_rtctl_stop();

	if (!chThdCreateStatic(_wa_control_thread, sizeof(_wa_control_thread), HIGHPRIO, control_thread, NULL)) {
		abort();
	}
	return 0;
}
Exemplo n.º 9
0
FluxTensorMethod::FluxTensorMethod(int nDs, int nDt, int nAs, int nAt, double thershold)
{
	this->threshold = thershold;
	this->nDs = nDs;
	this->nDt = nDt;
	this->nAs = nAs;
	this->nAt = nAt;
	init_filters();
}
Exemplo n.º 10
0
void myAudioStream::changePayload(const QString & payload)
{
    stop_ticker();
    unlink_filters();
    destroy_filters();

    init_filters(payload);
    link_filters();
    start_ticker();
}
Exemplo n.º 11
0
Settings_window::Settings_window(QWidget *parent) 
:	QDialog(parent),
	ui_(new ::Ui::SettingsWindow),
	simple_size_filter_view_()
{
	ui_->setupUi(this);
	ui_->filters_box->removeItem(0);// It was obligatory in Qt Designer. Remove it.

	QObject::connect(ui_->apply_btn, SIGNAL(clicked()),
		this, SLOT(apply_btn_clicked()));

	QObject::connect(ui_->cancel_btn, SIGNAL(clicked()),
		this, SLOT(cancel_btn_clicked()));

	init_filters();
}
Exemplo n.º 12
0
static int redirect_init(void)
{
	regex_t *filter;

	/* load the TM API */
	if (load_tm_api(&rd_tmb)!=0) {
		LOG(L_ERR, "ERROR:uac_redirect:init: can't load TM API\n");
		goto error;
	}

	/* init filter */
	init_filters();

	/* what's the default rule? */
	if (def_filter_s) {
		if ( !strcasecmp(def_filter_s,ACCEPT_RULE_STR) ) {
			set_default_rule( ACCEPT_RULE );
		} else if ( !strcasecmp(def_filter_s,DENY_RULE_STR) ) {
			set_default_rule( DENY_RULE );
		} else {
			LOG(L_ERR,"ERROR:uac_redirect:init: unknown default "
				"filter <%s>\n",def_filter_s);
		}
	}

	/* if accept filter specify, compile it */
	if (regexp_compile(accept_filter_s, &filter)<0) {
		LOG(L_ERR,"ERROR:uac_redirect:init: cannot init accept filter\n");
		goto error;
	}
	add_default_filter( ACCEPT_FILTER, filter);

	/* if deny filter specify, compile it */
	if (regexp_compile(deny_filter_s, &filter)<0) {
		LOG(L_ERR,"ERROR:uac_redirect:init: cannot init deny filter\n");
		goto error;
	}
	add_default_filter( DENY_FILTER, filter);

	return 0;
error:
	return -1;
}
Exemplo n.º 13
0
PyObject*
_PyWarnings_InitWithConfig(const _PyCoreConfig *config)
{
    PyObject *m;

    m = PyModule_Create(&warningsmodule);
    if (m == NULL)
        return NULL;

    if (_PyRuntime.warnings.filters == NULL) {
        _PyRuntime.warnings.filters = init_filters(config);
        if (_PyRuntime.warnings.filters == NULL)
            return NULL;
    }
    Py_INCREF(_PyRuntime.warnings.filters);
    if (PyModule_AddObject(m, "filters", _PyRuntime.warnings.filters) < 0)
        return NULL;

    if (_PyRuntime.warnings.once_registry == NULL) {
        _PyRuntime.warnings.once_registry = PyDict_New();
        if (_PyRuntime.warnings.once_registry == NULL)
            return NULL;
    }
    Py_INCREF(_PyRuntime.warnings.once_registry);
    if (PyModule_AddObject(m, "_onceregistry",
                           _PyRuntime.warnings.once_registry) < 0)
        return NULL;

    if (_PyRuntime.warnings.default_action == NULL) {
        _PyRuntime.warnings.default_action = PyUnicode_FromString("default");
        if (_PyRuntime.warnings.default_action == NULL)
            return NULL;
    }
    Py_INCREF(_PyRuntime.warnings.default_action);
    if (PyModule_AddObject(m, "_defaultaction",
                           _PyRuntime.warnings.default_action) < 0)
        return NULL;

    _PyRuntime.warnings.filters_version = 0;
    return m;
}
Exemplo n.º 14
0
static inline ia_seq_t* analyze_init( ia_param_t* p )
{
    int j;
    ia_seq_t* ias = ia_seq_open( p );

    if( ias == NULL ) {
        fprintf( stderr, "ERROR: analyze_init(): couldnt open ia_seq\n" );
        return NULL;
    }

    init_filters();

    /* call any init functions */
    for ( j = 0; p->filter[j] != 0; j++ )
    {
        if( filters.init[p->filter[j]] )
            filters.init[p->filter[j]]( ias, ias->fparam[p->filter[j]] );
    }

    return ias;
}
Exemplo n.º 15
0
PyMODINIT_FUNC
_PyWarnings_Init(void)
{
    PyObject *m;

    m = PyModule_Create(&warningsmodule);
    if (m == NULL)
        return NULL;

    if (_filters == NULL) {
        _filters = init_filters();
        if (_filters == NULL)
            return NULL;
    }
    Py_INCREF(_filters);
    if (PyModule_AddObject(m, "filters", _filters) < 0)
        return NULL;

    if (_once_registry == NULL) {
        _once_registry = PyDict_New();
        if (_once_registry == NULL)
            return NULL;
    }
    Py_INCREF(_once_registry);
    if (PyModule_AddObject(m, "_onceregistry", _once_registry) < 0)
        return NULL;

    if (_default_action == NULL) {
        _default_action = PyUnicode_FromString("default");
        if (_default_action == NULL)
            return NULL;
    }
    Py_INCREF(_default_action);
    if (PyModule_AddObject(m, "_defaultaction", _default_action) < 0)
        return NULL;

    _filters_version = 0;
    return m;
}
Exemplo n.º 16
0
int main(int argc, char **argv)
{
    int ret;
    AVPacket packet;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    if (!frame || !filt_frame) {
        perror("Could not allocate frame");
        exit(1);
    }
    if (argc != 2) {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        exit(1);
    }

    avcodec_register_all();
    av_register_all();
    avfilter_register_all();

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;

    /* read all packets */
    while (1) {
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;

        if (packet.stream_index == video_stream_index) {
            avcodec_get_frame_defaults(frame);
            got_frame = 0;
            ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");
                break;
            }

            if (got_frame) {
                frame->pts = av_frame_get_best_effort_timestamp(frame);

                /* push the decoded frame into the filtergraph */
                if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
                    break;
                }

                /* pull filtered frames from the filtergraph */
                while (1) {
                    ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;
                    display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);
                    av_frame_unref(filt_frame);
                }
                av_frame_unref(frame);
            }
        }
        av_free_packet(&packet);
    }
end:
    avfilter_graph_free(&filter_graph);
    if (dec_ctx)
        avcodec_close(dec_ctx);
    avformat_close_input(&fmt_ctx);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);

    if (ret < 0 && ret != AVERROR_EOF) {
        char buf[1024];
        av_strerror(ret, buf, sizeof(buf));
        fprintf(stderr, "Error occurred: %s\n", buf);
        exit(1);
    }

    exit(0);
}
Exemplo n.º 17
0
/*!*****************************************************************************
 *******************************************************************************
\note  init_sensor_processing
\date  May 2000
   
\remarks 

          Initializes all sensory processing

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

     none

 ******************************************************************************/
int
init_sensor_processing(void)

{
  
  int i,j;
  FILE      *in;
  char       string[100];
  static int firsttime = TRUE;

  if (firsttime) {
    firsttime = FALSE;
    joint_lin_rot     = my_matrix(1,n_dofs,1,6);
    pos_polar         = my_vector(1,n_dofs);
    load_polar        = my_vector(1,n_dofs);
    joint_raw_state   = (SL_Jstate *) 
      my_calloc((unsigned long)(n_dofs+1),sizeof(SL_Jstate),MY_STOP);
    misc_raw_sensor   = (double *) 
      my_calloc((unsigned long)(n_misc_sensors+1),sizeof(double),MY_STOP);
    fth = (Filter *)
      my_calloc((unsigned long)(n_dofs+1),sizeof(Filter),MY_STOP);
    fthd = (Filter *)
      my_calloc((unsigned long)(n_dofs+1),sizeof(Filter),MY_STOP);
    fthdd = (Filter *)
      my_calloc((unsigned long)(n_dofs+1),sizeof(Filter),MY_STOP);
    fload = (Filter *)
      my_calloc((unsigned long)(n_dofs+1),sizeof(Filter),MY_STOP);
    fmisc_sensor = (Filter *)
      my_calloc((unsigned long)(n_misc_sensors+1),sizeof(Filter),MY_STOP);
  }

  /* initalizes translation to and from units */
  if (!init_user_sensor_processing())
    return FALSE;

  /* initialize filtering */
  if (!init_filters())
    return FALSE;

  /* read several variables from files */

  /* first, get the calibration values for dealing with the linear to
     rotary conversion */
  if (!read_sensor_calibration(config_files[SENSORCALIBRATION],
      joint_lin_rot,pos_polar,load_polar))
    return FALSE;

  /* second, get the max, min , and offsets of the position sensors */
  if (!read_sensor_offsets(config_files[SENSOROFFSETS]))
    return FALSE;

  /* third, get the filter cutoff values for all variable */
  if (!read_sensor_filters(config_files[SENSORFILTERS]))
    return FALSE;

  /* add function to man pages */
  addToMan("where_off","sensor readings without offsets",where_off);
  addToMan("where_raw","raw sensor readings",where_raw);
  addToMan("monitor_min_max","records min/max values of sensors",monitor_min_max);

  if (!real_robot_flag)
    addToMan("toggle_filter","toggles sensor filtering on and off",toggle_filter);


  /* make raw variables available for output */

  for (i=1; i<=n_dofs; ++i) {
    sprintf(string,"%s_rth",joint_names[i]);
    addVarToCollect((char *)&(joint_raw_state[i].th),string,"rad", DOUBLE,FALSE);
    sprintf(string,"%s_rthd",joint_names[i]);
    addVarToCollect((char *)&(joint_raw_state[i].thd),string,"rad/s", DOUBLE,FALSE);
    sprintf(string,"%s_rload",joint_names[i]);
    addVarToCollect((char *)&(joint_raw_state[i].load),string,"Nm", DOUBLE,FALSE);
  }

  for (i=1; i<=n_misc_sensors; ++i) {
    sprintf(string,"%s_r",misc_sensor_names[i]);
    addVarToCollect((char *)&(misc_raw_sensor[i]),string,"-", DOUBLE,FALSE);
  }
  

  return TRUE;
  
}
Exemplo n.º 18
0
int main(int argc, char **argv)
{
    //curses
    int color_pair;
    if(initscr() == NULL){
        fprintf(stderr, "init failure\n");
        exit(EXIT_FAILURE);
    }
    /* start_colorは色属性を使用するときは最初に必ず実行する.
       initscrの直後に実行するのがよい習慣らしい. */
    if(has_colors() == FALSE || start_color() == ERR){
        endwin();
        fprintf(stderr, "This term seems not to having Color\n");
        exit(EXIT_FAILURE);
    }

    if(signal(SIGINT, sig_handler) == SIG_ERR ||
            signal(SIGQUIT, sig_handler) == SIG_ERR){
        fprintf(stderr, "signal failure\n");
        exit(EXIT_FAILURE);
    }
    curs_set(0);

    /* 色のペアを作る */
    color_pair = 1;
    for(color_pair = 1; color_pair < 256; color_pair++){
        init_pair(color_pair, color_pair, color_pair);
    }

    refresh();

    char filter_descr[10000];
    int w, h;
    w = 80;//COLS;
    h = 25;//LINES;
    bak = malloc(sizeof (int) * LINES*COLS+1);
        sprintf(filter_descr, "scale=%d:%d", w, h);



    int ret;
    AVPacket packet;
    AVFrame frame;
    int got_frame;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        exit(1);
    }

    avcodec_register_all();
    av_register_all();
    avfilter_register_all();

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;

    /* read all packets */
    while (1) {
        AVFilterBufferRef *picref;
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;

        if (packet.stream_index == video_stream_index) {
            avcodec_get_frame_defaults(&frame);
            got_frame = 0;
            ret = avcodec_decode_video2(dec_ctx, &frame, &got_frame, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");
                break;
            }

            if (got_frame) {
                frame.pts = av_frame_get_best_effort_timestamp(&frame);

                /* push the decoded frame into the filtergraph */
                if (av_buffersrc_add_frame(buffersrc_ctx, &frame, 0) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
                    break;
                }

                /* pull filtered pictures from the filtergraph */
                while (repeat_flag) {
                    ret = av_buffersink_get_buffer_ref(buffersink_ctx, &picref, 0);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;

                    if (picref) {
                        display_picref(picref, buffersink_ctx->inputs[0]->time_base);
                        avfilter_unref_bufferp(&picref);
                    }
                }
            }
        }
        av_free_packet(&packet);
    }
end:
    endwin();
    avfilter_graph_free(&filter_graph);
    if (dec_ctx)
        avcodec_close(dec_ctx);
    avformat_close_input(&fmt_ctx);

    if (ret < 0 && ret != AVERROR_EOF) {
        char buf[1024];
        av_strerror(ret, buf, sizeof(buf));
        fprintf(stderr, "Error occurred: %s\n", buf);
        exit(1);
    }

    exit(0);
}
Exemplo n.º 19
0
int bcf_sr_add_reader(bcf_srs_t *files, const char *fname)
{
    htsFile* file_ptr = hts_open(fname, "r");
    if ( ! file_ptr ) {
        files->errnum = open_failed;
        return 0;
    }

    files->has_line = (int*) realloc(files->has_line, sizeof(int)*(files->nreaders+1));
    files->has_line[files->nreaders] = 0;
    files->readers  = (bcf_sr_t*) realloc(files->readers, sizeof(bcf_sr_t)*(files->nreaders+1));
    bcf_sr_t *reader = &files->readers[files->nreaders++];
    memset(reader,0,sizeof(bcf_sr_t));

    reader->file = file_ptr;

    files->errnum = 0;

    if ( files->require_index )
    {
        if ( reader->file->format.format==vcf )
        {
            if ( reader->file->format.compression!=bgzf )
            {
                files->errnum = not_bgzf;
                return 0;
            }

            reader->tbx_idx = tbx_index_load(fname);
            if ( !reader->tbx_idx )
            {
                files->errnum = idx_load_failed;
                return 0;
            }

            reader->header = bcf_hdr_read(reader->file);
        }
        else if ( reader->file->format.format==bcf )
        {
            if ( reader->file->format.compression!=bgzf )
            {
                files->errnum = not_bgzf;
                return 0;
            }

            reader->header = bcf_hdr_read(reader->file);

            reader->bcf_idx = bcf_index_load(fname);
            if ( !reader->bcf_idx )
            {
                files->errnum = idx_load_failed;
                return 0;
            }
        }
        else
        {
            files->errnum = file_type_error;
            return 0;
        }
    }
    else
    {
        if ( reader->file->format.format==bcf || reader->file->format.format==vcf )
        {
            reader->header = bcf_hdr_read(reader->file);
        }
        else
        {
            files->errnum = file_type_error;
            return 0;
        }
        files->streaming = 1;
    }
    if ( files->streaming && files->nreaders>1 )
    {
        files->errnum = api_usage_error;
        fprintf(stderr,"[%s:%d %s] Error: %d readers, yet require_index not set\n", __FILE__,__LINE__,__FUNCTION__,files->nreaders);
        return 0;
    }
    if ( files->streaming && files->regions )
    {
        files->errnum = api_usage_error;
        fprintf(stderr,"[%s:%d %s] Error: cannot tabix-jump in streaming mode\n", __FILE__,__LINE__,__FUNCTION__);
        return 0;
    }
    if ( !reader->header )
    {
        files->errnum = header_error;
        return 0;
    }

    reader->fname = fname;
    if ( files->apply_filters )
        reader->filter_ids = init_filters(reader->header, files->apply_filters, &reader->nfilter_ids);

    // Update list of chromosomes
    if ( !files->explicit_regs && !files->streaming )
    {
        int n,i;
        const char **names = reader->tbx_idx ? tbx_seqnames(reader->tbx_idx, &n) : bcf_hdr_seqnames(reader->header, &n);
        for (i=0; i<n; i++)
        {
            if ( !files->regions )
                files->regions = _regions_init_string(names[i]);
            else
                _regions_add(files->regions, names[i], -1, -1);
        }
        free(names);
    }

    return 1;
}
Exemplo n.º 20
0
int main(int argc, char **argv)
{
    int ret;
    AVPacket packet = { .data = NULL, .size = 0 };
    AVFrame *frame = NULL;
    enum AVMediaType type;
    unsigned int stream_index;
    unsigned int i;
    int got_frame;
    int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);

    if (argc != 3)
    {
        av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]);
        return 1;
    }

    av_register_all();
    avfilter_register_all();

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = open_output_file(argv[2])) < 0)
        goto end;
    if ((ret = init_filters()) < 0)
        goto end;

    /* read all packets */
    while (1)
    {
        if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
            break;
        stream_index = packet.stream_index;
        type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type;
        av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
               stream_index);

        if (filter_ctx[stream_index].filter_graph)
        {
            av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
            frame = av_frame_alloc();
            if (!frame)
            {
                ret = AVERROR(ENOMEM);
                break;
            }
            av_packet_rescale_ts(&packet,
                                 ifmt_ctx->streams[stream_index]->time_base,
                                 ifmt_ctx->streams[stream_index]->codec->time_base);
            dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
                       avcodec_decode_audio4;
            ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame,
                           &got_frame, &packet);
            if (ret < 0)
            {
                av_frame_free(&frame);
                av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
                break;
            }

            if (got_frame)
            {
                frame->pts = av_frame_get_best_effort_timestamp(frame);
                ret = filter_encode_write_frame(frame, stream_index);
                av_frame_free(&frame);
                if (ret < 0)
                    goto end;
            }
            else
            {
                av_frame_free(&frame);
            }
        }
        else
        {
            /* remux this frame without reencoding */
            av_packet_rescale_ts(&packet,
                                 ifmt_ctx->streams[stream_index]->time_base,
                                 ofmt_ctx->streams[stream_index]->time_base);

            ret = av_interleaved_write_frame(ofmt_ctx, &packet);
            if (ret < 0)
                goto end;
        }
        av_packet_unref(&packet);
    }

    /* flush filters and encoders */
    for (i = 0; i < ifmt_ctx->nb_streams; i++)
    {
        /* flush filter */
        if (!filter_ctx[i].filter_graph)
            continue;
        ret = filter_encode_write_frame(NULL, i);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n");
            goto end;
        }

        /* flush encoder */
        ret = flush_encoder(i);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
            goto end;
        }
    }

    av_write_trailer(ofmt_ctx);
end:
    av_packet_unref(&packet);
    av_frame_free(&frame);
    for (i = 0; i < ifmt_ctx->nb_streams; i++)
    {
        avcodec_close(ifmt_ctx->streams[i]->codec);
        if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec)
            avcodec_close(ofmt_ctx->streams[i]->codec);
        if (filter_ctx && filter_ctx[i].filter_graph)
            avfilter_graph_free(&filter_ctx[i].filter_graph);
    }
    av_free(filter_ctx);
    avformat_close_input(&ifmt_ctx);
    if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
        avio_closep(&ofmt_ctx->pb);
    avformat_free_context(ofmt_ctx);

    if (ret < 0)
        av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));

    return ret ? 1 : 0;
}
int main_dummy(int argc, char **argv)
#endif
{
    AVOutputFormat *ofmt = NULL;
    AVFormatContext *inVideoFmtCtx = NULL, *inAudioFmtCtx = NULL, *outFmtCtx = NULL;
    AVPacket pkt;
    const char *inVideo_filename, *inAudio_filename, *out_filename;
    int ret, i;

    if (argc < 3) {
        printf("usage: %s input output\n"
            "API example program to remux a media file with libavformat and libavcodec.\n"
            "The output format is guessed according to the file extension.\n"
            "\n", argv[0]);
        return 1;
    }

    inVideo_filename = argv[1];
    inAudio_filename = argv[2];
    out_filename = argv[3];

    av_register_all();

    /* =============== OPEN STREAMS ================*/

    if ((ret = open_input_file2(argv[1], &inVideoFmtCtx)) < 0)
        goto end;

    if ((ret = open_input_file2(argv[2], &inAudioFmtCtx)) < 0)
        goto end;

    /* ========== ALLOCATE OUTPUT CONTEXT ==========*/

    avformat_alloc_output_context2(&outFmtCtx, NULL, NULL, out_filename);
    if (!outFmtCtx) {
        fprintf(stderr, "Could not create output context\n");
        ret = AVERROR_UNKNOWN;
        goto end;
    }

    ofmt = outFmtCtx->oformat;

    /* =============== SETUP VIDEO CODEC ================*/
    for (i = 0; i < inVideoFmtCtx->nb_streams; i++) {
        AVStream *in_stream = inVideoFmtCtx->streams[i];
        AVStream *out_stream = avformat_new_stream(outFmtCtx, in_stream->codec->codec);
        if (!out_stream) {
            fprintf(stderr, "Failed allocating output stream\n");
            ret = AVERROR_UNKNOWN;
            goto end;
        }

        ret = avcodec_copy_context(out_stream->codec, in_stream->codec);
        if (ret < 0) {
            fprintf(stderr, "Failed to copy context from input to output stream codec context\n");
            goto end;
        }
        out_stream->codec->codec_tag = 0;
        if (outFmtCtx->oformat->flags & AVFMT_GLOBALHEADER)
            out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }

    /* =============== SETUP AUDIO CODEC ================*/
    for (i = 0; i < inAudioFmtCtx->nb_streams; i++) {
        setup_mp3_audio_codec(outFmtCtx);
    }

    av_dump_format(outFmtCtx, 0, out_filename, 1);

    if (!(ofmt->flags & AVFMT_NOFILE)) {
        ret = avio_open(&outFmtCtx->pb, out_filename, AVIO_FLAG_WRITE);
        if (ret < 0) {
            fprintf(stderr, "Could not open output file '%s'", out_filename);
            goto end;
        }
    }

    ret = avformat_write_header(outFmtCtx, NULL);
    if (ret < 0) {
        fprintf(stderr, "Error occurred when opening output file\n");
        goto end;
    }


    /* =============== SETUP FILTERS ================*/

    init_filters(inAudioFmtCtx, outFmtCtx);

    AVStream *in_stream, *out_stream;
    AVFrame* frame;

    while (1) {        

        /* =============== VIDEO STREAM ================*/
        ret = av_read_frame(inVideoFmtCtx, &pkt);
        if (ret < 0)
            break;

        in_stream = inVideoFmtCtx->streams[pkt.stream_index];
        out_stream = outFmtCtx->streams[pkt.stream_index];

        log_packet(inVideoFmtCtx, &pkt, "in");

        /* copy packet */
        pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
        pkt.duration = (int)av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
        pkt.pos = -1;
        log_packet(outFmtCtx, &pkt, "out");

        ret = av_interleaved_write_frame(outFmtCtx, &pkt);
        if (ret < 0) {
            fprintf(stderr, "Error muxing packet\n");
            break;
        }
        av_free_packet(&pkt);


        /* =============== AUDIO STREAM ================*/

#if 0
        ret = av_read_frame(inAudioFmtCtx, &pkt);
        if (ret < 0)
            break;
        in_stream = inAudioFmtCtx->streams[pkt.stream_index];

        pkt.stream_index++;
        out_stream = outFmtCtx->streams[pkt.stream_index];

        log_packet(inAudioFmtCtx, &pkt, "in");

        /* copy packet */
        pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
        pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
        pkt.pos = -1;
        log_packet(outFmtCtx, &pkt, "out");

        ret = av_interleaved_write_frame(outFmtCtx, &pkt);
        if (ret < 0) {
            fprintf(stderr, "Error muxing packet\n");
            break;
        }
        av_free_packet(&pkt);
#else

        if ((ret = av_read_frame(inAudioFmtCtx, &pkt)) < 0)
            break;
        int streamIndex = pkt.stream_index;
        int gotFrame;

        if (_filterCtx[streamIndex].FilterGraph) {
            av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
            frame = av_frame_alloc();
            if (!frame) {
                ret = AVERROR(ENOMEM);
                break;
            }
            av_packet_rescale_ts(&pkt, inAudioFmtCtx->streams[streamIndex]->time_base,
                inAudioFmtCtx->streams[streamIndex]->codec->time_base);
            ret = avcodec_decode_audio4(inAudioFmtCtx->streams[streamIndex]->codec, frame,
                &gotFrame, &pkt);
            if (ret < 0) {
                av_frame_free(&frame);
                av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
                break;
            }

            if (gotFrame) {
                frame->pts = av_frame_get_best_effort_timestamp(frame);
                ret = filter_encode_write_frame(frame, inAudioFmtCtx, outFmtCtx, streamIndex);
                av_frame_free(&frame);
                if (ret < 0)
                    goto end;
            }
            else {
                av_frame_free(&frame);
            }
        }
        else {
            /* remux this frame without reencoding */
            av_packet_rescale_ts(&pkt,
                inAudioFmtCtx->streams[streamIndex]->time_base,
                outFmtCtx->streams[streamIndex+1]->time_base);

            ret = av_interleaved_write_frame(outFmtCtx, &pkt);
            if (ret < 0)
                goto end;
        }
        av_free_packet(&pkt);
#endif // 0

    }

    av_write_trailer(outFmtCtx);
end:

    av_free_packet(&pkt);
    av_frame_free(&frame);
    for (i = 0; i < inAudioFmtCtx->nb_streams; i++) {
        avcodec_close(inAudioFmtCtx->streams[i]->codec);
        if (outFmtCtx && outFmtCtx->nb_streams > i && outFmtCtx->streams[i] && outFmtCtx->streams[i]->codec)
            avcodec_close(outFmtCtx->streams[i]->codec);
        if (_filterCtx && _filterCtx[i].FilterGraph)
            avfilter_graph_free(&_filterCtx[i].FilterGraph);
    }
    av_free(_filterCtx);

    avformat_close_input(&inVideoFmtCtx);
    avformat_close_input(&inAudioFmtCtx);

    /* close output */
    if (outFmtCtx && !(ofmt->flags & AVFMT_NOFILE))
        avio_closep(&outFmtCtx->pb);
    avformat_free_context(outFmtCtx);

    if (ret < 0 && ret != AVERROR_EOF) {
        //fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
        return 1;
    }

    return 0;
}
Exemplo n.º 22
0
int dmpTask::initialize()
{
double freq;
int i;
int ans = 999;

  start_time_ = 0.0;
  
  // Make sure that everything is clear
  if (vnames_CBi != NULL)
  {
    for (i = 1; i <= dof_CBi; i++)
      free((void *) vnames_CBi[i]);
    free((void *) vnames_CBi);
    vnames_CBi = NULL;
  }
  if (units_CBi != NULL)
  {
    for (i = 1; i <= dof_CBi; i++)
      free((void *) units_CBi[i]);
    free((void *) units_CBi);
    units_CBi = NULL;
  }
  if (CBi_traj != NULL)
  {
    my_free_matrix(CBi_traj, 1, n_CBi, 1, dof_CBi);
    CBi_traj = NULL;
  }
  if (vnames_Kinect != NULL)
  {
    for (i = 1; i <= dof_Kinect; i++)
      free((void *) vnames_Kinect[i]);
    free((void *) vnames_Kinect);
    vnames_Kinect = NULL;
  }
  vnames_Kinect = NULL;
  if (units_Kinect != NULL)
  {
    for (i = 1; i <= dof_Kinect; i++)
      free((void *) units_Kinect[i]);
    free((void *) units_Kinect);
    units_Kinect = NULL;
  }
  if (Kinect_traj != NULL)
  {
    my_free_matrix(Kinect_traj, 1, n_Kinect, 1, dof_Kinect);
    Kinect_traj = NULL;
  }
  if (DMP_object != NULL)
  {
    delete DMP_object;
    DMP_object = NULL;
  }

  // Read robot trajectory
  // mrdplot_convert(CBi_traj_file, &CBi_traj, &vnames_CBi, &units_CBi, &freq, &dof_CBi, &n_CBi);
  mrdplot_read(CBi_traj_file, &CBi_traj, &vnames_CBi, &units_CBi, &freq, &dof_CBi, &n_CBi);
  if (!set_active_dofs(vnames_CBi, dof_CBi, active_dofs))
    return FALSE;

  printf("%d active DoFs:", active_dofs[0]);
  for (i = 2; i <= active_dofs[0]+1; i++)
  {
    if (!((i-2)%8))
      printf("\n");
    printf("%s, ", vnames_CBi[i]);
  }
  printf("\n\n");

  // Read Kinect trajectory
  // mrdplot_convert(Kinect_traj_file, &Kinect_traj, &vnames_Kinect, &units_Kinect, &freq, &dof_Kinect, &n_Kinect);
  mrdplot_read(Kinect_traj_file, &Kinect_traj, &vnames_Kinect, &units_Kinect, &freq, &dof_Kinect, &n_Kinect);

  // Filter Kinect trajectory if desired
  if (Kinect_traj != NULL && filter_Kinect_data)
  {
    if (!init_filters())
      return FALSE;
    for (int i = 1; i <= 19; i++)
      fth[i].cutoff = 9;
    for (int i = 1; i <= 19; i++)
    {
      fth[i].raw[0] = fth[i].raw[1] = fth[i].raw[2] = Kinect_traj[1][i+1];
      fth[i].filt[0] = fth[i].filt[1] = fth[i].filt[2] = Kinect_traj[1][i+1];
    }
    for (int j = 1; j <= n_Kinect; j++)
      for (int i = 1; i <= 19; i++)
        Kinect_traj[j][i+1] = filt(Kinect_traj[j][i+1], &fth[i]);
  }

  // Compute DMP for robot trajectory
  if (DMP_object != NULL)
    delete DMP_object;
  // DMP_object = new DMP_structure(DMP_file);
  DMP_object = new DMP_structure(active_dofs[0], 50, 2.0, 12.0, 3.0);
  printf("\n");
  if (!DMP_object->example_Matrix(CBi_traj, n_CBi, dof_CBi))
    return FALSE;
  DMP_object->DMP_estimate(0);
  // DMP_object->DMP_param_print();
  printf("\n");

  // Initialize DMP integration
  for (int i = 1; i <= active_dofs[0]; i++)
  {
    initial_positions[i] = CBi_traj[1][i+1];
    initial_velocities[i] = 0.0;
  }
  DMP_object->set_initial_DMP_state(&(initial_positions[1]), &(initial_velocities[1]));

  // include this file to define contact points (needed to compute center of pressure)
#include "LEKin_contact.h"
  
  // prepare going to the default posture
  bzero((char *)&(target_[1]),N_DOFS*sizeof(target_[1]));
  for (i = 1; i <= N_DOFS; i++)
    target_[i] = joint_default_state[i];
  target_[L_EB].th = target_[R_EB].th = 0.05;
  target_[B_TFE].th = 0.2;  

  for (int i = 1; i <= active_dofs[0]; i++)
  {
    target_[active_dofs[i]].th = initial_positions[i];
    target_[active_dofs[i]].thd = 0.0;
    target_[active_dofs[i]].thdd = 0.0;
    target_[active_dofs[i]].uff = 0.0;
  }

  bool there = true;
  for (int i = 1; i <= B_HR; i++)
    if (fabs(target_[i].th - joint_des_state[i].th) > 1.0e-3)
    {
      there = false;
      break;
    }
  // go to the target using inverse dynamics (ID)int SampleTask::changeParameters()
  if (!there)
  {
    if (!go_target_wait_ID(target_))
    {
      return FALSE;
    }
  }

  // ready to go
  while (ans == 999)
  {
    if (!get_int(const_cast<char*>("Enter 1 to start or anthing else to abort ..."), ans, &ans))
    {
      return FALSE;
    }
  }
  
  // only go when user really types the right thing
  if (ans != 1) 
  {
    return FALSE;
  }

  start_time_ = task_servo_time;
  printf("start time = %.3f, task_servo_time = %.3f\n", start_time_, task_servo_time);

  return TRUE;
}
int imu_init(LoggerConfig *loggerConfig)
{
    imu_device_init();
    init_filters(loggerConfig);
    return 1;
}
int imu_soft_init(LoggerConfig *loggerConfig)
{
    init_filters(loggerConfig);
    return 1;
}
Exemplo n.º 25
0
    /*
     * Class:     com_jpou_meditor_ffmpeg_trans
     * Method:    startTrans
     * Signature: (Ljava/lang/String;Ljava/lang/String;)Z
     */
    JNIEXPORT jboolean JNICALL Java_com_jpou_ffmpeg_Transcoding_startTrans
        (JNIEnv *env, jobject clazz, jstring input, jstring output) {
            int ret;
            AVPacket packet = { .data = NULL, .size = 0 };
            AVFrame *frame = NULL;
            enum AVMediaType type;
            unsigned int stream_index;
            unsigned int i;
            int got_frame;
            int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);

            char *input_str, *output_str;
            input_str = (*env)->GetStringUTFChars(env, input, 0);
            output_str = (*env)->GetStringUTFChars(env, output, 0);
            LOGI("input_str ~ : %s -------------------", input_str);
            LOGI("output_str ~ : %s -------------------", output_str);


            if ((input == NULL) || (output == NULL)) {
                LOGI("input_str or output_str is null");
                return (jboolean)0;
            }

            av_register_all();
            avfilter_register_all();

            if ((ret = open_input_file(input_str)) < 0) {
                LOGI("open_input_file error");
                goto end;
            }
            if ((ret = open_output_file(output_str)) < 0) {
                LOGI("open_output_file error");
                goto end;
            }
            LOGI("init_filters ----------------");
            if ((ret = init_filters()) < 0) {
                LOGI("init_filters error");
                goto end;
            }

            /* read all packets */
            LOGI("start av_read_frame ----------------");
            while (1) {
                if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
                    break;
                stream_index = packet.stream_index;
                type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type;
                LOGI("Demuxer gave frame of stream_index %u\n",
                        stream_index);

                if (filter_ctx[stream_index].filter_graph) {
                    av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
                    frame = av_frame_alloc();
                    if (!frame) {
                        ret = AVERROR(ENOMEM);
                        break;
                    }
                    av_packet_rescale_ts(&packet,
                            ifmt_ctx->streams[stream_index]->time_base,
                            ifmt_ctx->streams[stream_index]->codec->time_base);
                    dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
                        avcodec_decode_audio4;
                    ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame,
                            &got_frame, &packet);
                    if (ret < 0) {
                        av_frame_free(&frame);
                        LOGI("Decoding failed\n");
                        break;
                    }

                    if (got_frame) {
                        frame->pts = av_frame_get_best_effort_timestamp(frame);
                        ret = filter_encode_write_frame(frame, stream_index);
                        av_frame_free(&frame);
                        if (ret < 0)
                            goto end;
                    } else {
                        av_frame_free(&frame);
                    }
                } else {
                    /* remux this frame without reencoding */
                    av_packet_rescale_ts(&packet,
                            ifmt_ctx->streams[stream_index]->time_base,
                            ofmt_ctx->streams[stream_index]->time_base);

                    ret = av_interleaved_write_frame(ofmt_ctx, &packet);
                    if (ret < 0)
                        goto end;
                }
                av_free_packet(&packet);
            }

            /* flush filters and encoders */
            for (i = 0; i < ifmt_ctx->nb_streams; i++) {
                /* flush filter */
                if (!filter_ctx[i].filter_graph)
                    continue;
                ret = filter_encode_write_frame(NULL, i);
                if (ret < 0) {
                    LOGI("Flushing filter failed\n");
                    goto end;
                }

                /* flush encoder */
                ret = flush_encoder(i);
                if (ret < 0) {
                    LOGI("Flushing encoder failed\n");
                    goto end;
                }
            }

            av_write_trailer(ofmt_ctx);
            return (jboolean)1;
end:
            av_free_packet(&packet);
            av_frame_free(&frame);
            for (i = 0; i < ifmt_ctx->nb_streams; i++) {
                avcodec_close(ifmt_ctx->streams[i]->codec);
                if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec)
                    avcodec_close(ofmt_ctx->streams[i]->codec);
                if (filter_ctx && filter_ctx[i].filter_graph)
                    avfilter_graph_free(&filter_ctx[i].filter_graph);
            }
            av_free(filter_ctx);
            avformat_close_input(&ifmt_ctx);
            if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
                avio_closep(&ofmt_ctx->pb);
            avformat_free_context(ofmt_ctx);

            /**
              if (ret < 0)
              av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));
              */
            return (jboolean)0;

        }

#ifdef __cplusplus
}
Exemplo n.º 26
0
int main(int argc, char **argv){
	extern char		*optarg;
	int				r, sel;
	fd_set			sset, rset;
#if defined(sun) || defined(__sun) || defined (__linux__)
	struct timeval		timeout;
#endif
	struct target_ipv6	targetipv6;

	static struct option longopts[] = {
		{"interface", required_argument, 0, 'i'},
		{"src-address", required_argument, 0, 's'},
		{"dst-address", required_argument, 0, 'd'},
		{"hop-limit", required_argument, 0, 'A'},
		{"dst-opt-hdr", required_argument, 0, 'u'},
		{"dst-opt-u-hdr", required_argument, 0, 'U'},
		{"hbh-opt-hdr", required_argument, 0, 'H'},
		{"frag-hdr", required_argument, 0, 'y'},
		{"link-src-addr", required_argument, 0, 'S'},
		{"link-dst-addr", required_argument, 0, 'D'},
		{"target", required_argument, 0, 't'},
		{"router", no_argument, 0, 'r'},
		{"solicited", no_argument, 0, 'c'},
		{"override", no_argument, 0, 'o'},
		{"target-addr-opt", required_argument, 0, 'E'},
		{"add-target-opt", no_argument, 0, 'e'},
		{"block-src-addr", required_argument, 0, 'j'},
		{"block-dst-addr", required_argument, 0, 'k'},
		{"block-link-src-addr", required_argument, 0, 'J'},
		{"block-link-dst-addr", required_argument, 0, 'K'},
		{"block-target-addr", required_argument, 0, 'w'},
		{"accept-src-addr", required_argument, 0, 'b'},
		{"accept-dst-addr", required_argument, 0, 'g'},
		{"accept-link-src-addr", required_argument, 0, 'B'},
		{"accept-link-dst-addr", required_argument, 0, 'G'},
		{"accept-target-addr", required_argument, 0, 'W'},
		{"flood-sources", required_argument, 0, 'F'},
		{"flood-targets", required_argument, 0, 'T'},
		{"loop", no_argument, 0, 'l'},
		{"sleep", required_argument, 0, 'z'},
		{"listen", no_argument, 0, 'L'},
		{"verbose", no_argument, 0, 'v'},
		{"help", no_argument, 0, 'h'},
		{0, 0, 0,  0 }
	};

	char shortopts[]= "i:s:d:A:u:U:H:y:S:D:t:roceE:j:k:J:K:w:b:g:B:G:W:T:F:lz:vhL";

	char option;

	if(argc<=1){
		usage();
		exit(EXIT_FAILURE);
	}

    hoplimit=255;

	/* Initialize filters structure */
	if(init_filters(&filters) == -1){
		puts("Error initializing internal data structure");
		exit(EXIT_FAILURE);
	}

	if(init_iface_data(&idata) == FAILURE){
		puts("Error initializing internal data structure");
		exit(EXIT_FAILURE);
	}

	while((r=getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
		option= r;

		switch(option) {
			case 'i':  /* Interface */
				strncpy(idata.iface, optarg, IFACE_LENGTH-1);
				idata.iface[IFACE_LENGTH-1]=0;
				idata.iface_f=TRUE;
				break;

			case 's':	/* IPv6 Source Address */
				if(idata.srcaddr_f){
					puts("Error: Multiple '-s' options have been specified");
					exit(EXIT_FAILURE);
				}

				if((charptr = strtok_r(optarg, "/", &lasts)) == NULL){
					puts("Error in Source Address");
					exit(EXIT_FAILURE);
				}

				if ( inet_pton(AF_INET6, charptr, &(idata.srcaddr)) <= 0){
					puts("inet_pton(): Source Address not valid");
					exit(EXIT_FAILURE);
				}

				idata.srcaddr_f = 1;
		
				if((charptr = strtok_r(NULL, " ", &lasts)) != NULL){
					idata.srcpreflen = atoi(charptr);
		
					if(idata.srcpreflen>128){
						puts("Prefix length error in IPv6 Source Address");
						exit(EXIT_FAILURE);
					}

					sanitize_ipv6_prefix(&(idata.srcaddr), idata.srcpreflen);
					idata.srcprefix_f=1;
				}

				break;
	    
			case 'd':	/* IPv6 Destination Address */
				strncpy( targetipv6.name, optarg, NI_MAXHOST);
				targetipv6.name[NI_MAXHOST-1]= 0;
				targetipv6.flags= AI_CANONNAME;

				if( (r=get_ipv6_target(&targetipv6)) != 0){

					if(r < 0){
						printf("Unknown Destination: %s\n", gai_strerror(targetipv6.res));
					}
					else{
						puts("Unknown Destination: No IPv6 address found for specified destination");
					}

					exit(1);
				}

				idata.dstaddr= targetipv6.ip6;
				idata.dstaddr_f = 1;
				break;

			case 'A':	/* Hop Limit */
				hoplimit= atoi(optarg);
				hoplimit_f=1;
				break;

			case 'y':	/* Fragment header */
				nfrags= atoi(optarg);
				if(nfrags < 8){
					puts("Error in Fragmentation option: Fragment Size must be at least 8 bytes");
					exit(EXIT_FAILURE);
				}
		
				nfrags = (nfrags +7) & 0xfff8;
				idata.fragh_f= 1;
				break;

			case 'u':	/* Destinations Options Header */
				if(ndstopthdr >= MAX_DST_OPT_HDR){
					puts("Too many Destination Options Headers");
					exit(EXIT_FAILURE);
				}

				hdrlen= atoi(optarg);
		
				if(hdrlen < 8){
					puts("Bad length in Destination Options Header");
					exit(EXIT_FAILURE);
				}
		    
				hdrlen = ((hdrlen+7)/8) * 8;
				dstopthdrlen[ndstopthdr]= hdrlen;

				if( (dstopthdr[ndstopthdr]= malloc(hdrlen)) == NULL){
					puts("Not enough memory for Destination Options Header");
					exit(EXIT_FAILURE);
				}

				ptrhdr= dstopthdr[ndstopthdr] + 2;
				ptrhdrend= dstopthdr[ndstopthdr] + hdrlen;

				while( ptrhdr < ptrhdrend){

					if( (ptrhdrend-ptrhdr)>257)
						pad= 257;
					else
						pad= ptrhdrend-ptrhdr;
			
					if(!insert_pad_opt(ptrhdr, ptrhdrend, pad)){
						puts("Destination Options Header Too Big");
						exit(EXIT_FAILURE);
					}
		    
					ptrhdr= ptrhdr + pad;
				}

				*(dstopthdr[ndstopthdr]+1)= (hdrlen/8)-1;
				ndstopthdr++;
				dstopthdr_f=1;
				break;

			case 'U':	/* Destination Options Header (Unfragmentable Part) */
				if(ndstoptuhdr >= MAX_DST_OPT_U_HDR){
					puts("Too many Destination Options Headers (Unfragmentable Part)");
					exit(EXIT_FAILURE);
				}

				hdrlen= atoi(optarg);
		
				if(hdrlen < 8){
					puts("Bad length in Destination Options Header (Unfragmentable Part)");
					exit(EXIT_FAILURE);
				}

				hdrlen = ((hdrlen+7)/8) * 8;
				dstoptuhdrlen[ndstoptuhdr]= hdrlen;
		
				if( (dstoptuhdr[ndstoptuhdr]= malloc(hdrlen)) == NULL){
					puts("Not enough memory for Destination Options Header (Unfragmentable Part)");
					exit(EXIT_FAILURE);
				}

				ptrhdr= dstoptuhdr[ndstoptuhdr]+2;
				ptrhdrend= dstoptuhdr[ndstoptuhdr] + hdrlen;
		
				while( ptrhdr < ptrhdrend){

					if( (ptrhdrend-ptrhdr)>257)
						pad= 257;
					else
						pad= ptrhdrend-ptrhdr;

					if(!insert_pad_opt(ptrhdr, ptrhdrend, pad)){
						puts("Destination Options Header (Unfragmentable Part) Too Big");
						exit(EXIT_FAILURE);
					}

					ptrhdr = ptrhdr + pad;
				}

				*(dstoptuhdr[ndstoptuhdr]+1)= (hdrlen/8) - 1;
				ndstoptuhdr++;
				dstoptuhdr_f=1;
				break;

			case 'H':	/* Hop-by-Hop Options Header */
				if(nhbhopthdr >= MAX_HBH_OPT_HDR){
					puts("Too many Hop-by-Hop Options Headers");
					exit(EXIT_FAILURE);
				}

				hdrlen= atoi(optarg);
		
				if(hdrlen < 8){
					puts("Bad length in Hop-by-Hop Options Header");
					exit(EXIT_FAILURE);
				}
		    
				hdrlen = ((hdrlen+7)/8) * 8;
				hbhopthdrlen[nhbhopthdr]= hdrlen;
		
				if( (hbhopthdr[nhbhopthdr]= malloc(hdrlen)) == NULL){
					puts("Not enough memory for Hop-by-Hop Options Header");
					exit(EXIT_FAILURE);
				}

				ptrhdr= hbhopthdr[nhbhopthdr] + 2;
				ptrhdrend= hbhopthdr[nhbhopthdr] + hdrlen;
		
				while( ptrhdr < ptrhdrend){

					if( (ptrhdrend-ptrhdr)>257)
						pad= 257;
					else
						pad= ptrhdrend-ptrhdr;

					if(!insert_pad_opt(ptrhdr, ptrhdrend, pad)){
						puts("Hop-by-Hop Options Header Too Big");
						exit(EXIT_FAILURE);
					}

					ptrhdr = ptrhdr + pad;
				}

				*(hbhopthdr[nhbhopthdr]+1)= (hdrlen/8) - 1;
				nhbhopthdr++;
				hbhopthdr_f=1;
				break;

			case 'S':	/* Source Ethernet address */
				if(ether_pton(optarg, &(idata.hsrcaddr), sizeof(idata.hsrcaddr)) == 0){
					puts("Error in Source link-layer address.");
					exit(EXIT_FAILURE);
				}
		
				idata.hsrcaddr_f = 1;
				break;

			case 'D':	/* Destination Ethernet Address */
				if(ether_pton(optarg, &(idata.hdstaddr), sizeof(idata.hdstaddr)) == 0){
					puts("Error in Source link-layer address.");
					exit(EXIT_FAILURE);
				}
		
				idata.hdstaddr_f = 1;
				break;

			case 't':	/* NA Target address */
				if((charptr = strtok_r(optarg, "/", &lasts)) == NULL){
					puts("Target Address not valid");
					exit(EXIT_FAILURE);
				}

				if ( inet_pton(AF_INET6, charptr, &targetaddr) <= 0){
					puts("inet_pton(): Target Address not valid");
					exit(EXIT_FAILURE);
				}

				targetaddr_f = 1;
		
				if((charptr = strtok_r(NULL, " ", &lasts)) != NULL){
					targetpreflen = atoi(charptr);
		
					if(targetpreflen>128){
						puts("Prefix length error in Target Address");
						exit(EXIT_FAILURE);
					}

					sanitize_ipv6_prefix(&targetaddr, targetpreflen);
					targetprefix_f=1;
				}

				break;

			case 'r':	/* "Router" flag */
				router_f = ND_NA_FLAG_ROUTER;
				break;
	
			case 'o':	/* "Override" flag */
				override_f = ND_NA_FLAG_OVERRIDE;
				break;	    	    

			case 'c':	/* Solicited flag */
				solicited_f = ND_NA_FLAG_SOLICITED;
				break;
		
			case 'E':	/* Target link-layer option */
				tllaopt_f = 1;
				if(ether_pton(optarg, &linkaddr[nlinkaddr], sizeof(struct ether_addr)) == 0){
					puts("Error in Source link-layer address option.");
					exit(EXIT_FAILURE);
				}

				nlinkaddr++;		
				tllaopta_f=1;
				break;

			case 'e':	/* Add target link-layer option */
				tllaopt_f = 1;
				break;

			case 'j':	/* IPv6 Source Address (block) filter */
				if(filters.nblocksrc >= MAX_BLOCK_SRC){
					puts("Too many IPv6 Source Address (block) filters.");
					exit(EXIT_FAILURE);
				}
	    
				if((pref = strtok_r(optarg, "/", &lasts)) == NULL){
					printf("Error in IPv6 Source Address (block) filter number %u.\n", \
												filters.nblocksrc+1);
					exit(EXIT_FAILURE);
				}

				if ( inet_pton(AF_INET6, pref, &(filters.blocksrc[filters.nblocksrc])) <= 0){
					printf("Error in IPv6 Source Address (block) filter number %u.", \
											    filters.nblocksrc+1);
					exit(EXIT_FAILURE);
				}

				if((charptr = strtok_r(NULL, " ", &lasts)) == NULL){
		    			filters.blocksrclen[filters.nblocksrc] = 128;
				}
				else{
					filters.blocksrclen[filters.nblocksrc] = atoi(charptr);

					if(filters.blocksrclen[filters.nblocksrc]>128){
						printf("Length error in IPv6 Source Address (block) filter number %u.\n", \
													filters.nblocksrc+1);
						exit(EXIT_FAILURE);
		    			}
				}

				sanitize_ipv6_prefix(&(filters.blocksrc[filters.nblocksrc]), filters.blocksrclen[filters.nblocksrc]);
				(filters.nblocksrc)++;
				break;

			case 'k':	/* IPv6 Destination Address (block) filter */
				if(filters.nblockdst >= MAX_BLOCK_DST){
					puts("Too many IPv6 Destination Address (block) filters.");
					exit(EXIT_FAILURE);
				}

				if((pref = strtok_r(optarg, "/", &lasts)) == NULL){
					printf("Error in IPv6 Destination Address (block) filter number %u.\n", \
													filters.nblockdst+1);
					exit(EXIT_FAILURE);
				}

				if ( inet_pton(AF_INET6, pref, &(filters.blockdst[filters.nblockdst])) <= 0){
					printf("Error in IPv6 Source Address (block) filter number %u.", \
											    filters.nblockdst+1);
					exit(EXIT_FAILURE);
				}

				if((charptr = strtok_r(NULL, " ", &lasts)) == NULL){
					filters.blockdstlen[filters.nblockdst] = 128;
				}
				else{
					filters.blockdstlen[filters.nblockdst] = atoi(charptr);
		
					if(filters.blockdstlen[filters.nblockdst]>128){
						printf("Length error in IPv6 Source Address (block) filter number %u.\n", \
													    filters.nblockdst+1);
						exit(EXIT_FAILURE);
					}
				}
		
				sanitize_ipv6_prefix(&(filters.blockdst[filters.nblockdst]), filters.blockdstlen[filters.nblockdst]);
				(filters.nblockdst)++;
				break;

			case 'J':	/* Link Source Address (block) filter */
				if(filters.nblocklinksrc > MAX_BLOCK_LINK_SRC){
					puts("Too many link-layer Source Address (accept) filters.");
					exit(EXIT_FAILURE);
				}

				if(ether_pton(optarg, &(filters.blocklinksrc[filters.nblocklinksrc]), sizeof(struct ether_addr)) == 0){
					printf("Error in link-layer Source Address (blick) filter number %u.\n", \
												    filters.nblocklinksrc+1);
					exit(EXIT_FAILURE);
				}
		
				(filters.nblocklinksrc)++;
				break;

			case 'K':	/* Link Destination Address (block) filter */
				if(filters.nblocklinkdst > MAX_BLOCK_LINK_DST){
					puts("Too many link-layer Destination Address (block) filters.");
					exit(EXIT_FAILURE);
				}

				if(ether_pton(optarg, &(filters.blocklinkdst[filters.nblocklinkdst]), sizeof(struct ether_addr)) == 0){
					printf("Error in link-layer Destination Address (blick) filter number %u.\n", \
												    filters.nblocklinkdst+1);
					exit(EXIT_FAILURE);
				}
		
				filters.nblocklinkdst++;
				break;

			case 'b':	/* IPv6 Source Address (accept) filter */
				if(filters.nacceptsrc > MAX_ACCEPT_SRC){
					puts("Too many IPv6 Source Address (accept) filters.");
					exit(EXIT_FAILURE);
				}

				if((pref = strtok_r(optarg, "/", &lasts)) == NULL){
					printf("Error in IPv6 Source Address (accept) filter number %u.\n", \
												filters.nacceptsrc+1);
					exit(EXIT_FAILURE);
				}

				if ( inet_pton(AF_INET6, pref, &(filters.acceptsrc[filters.nacceptsrc])) <= 0){
					printf("Error in IPv6 Source Address (accept) filter number %u.\n", \
												filters.nacceptsrc+1);
					exit(EXIT_FAILURE);
				}
		
				if((charptr = strtok_r(NULL, " ", &lasts)) == NULL){
					filters.acceptsrclen[filters.nacceptsrc] = 128;
				}
				else{
					filters.acceptsrclen[filters.nacceptsrc] = atoi(charptr);

					if(filters.acceptsrclen[filters.nacceptsrc]>128){
						printf("Length error in IPv6 Source Address (accept) filter number %u.\n", \
														filters.nacceptsrc+1);
						exit(EXIT_FAILURE);
					}
				}

				sanitize_ipv6_prefix(&(filters.acceptsrc[filters.nacceptsrc]), filters.acceptsrclen[filters.nacceptsrc]);
				(filters.nacceptsrc)++;
				filters.acceptfilters_f=1;
				break;


			case 'g':	/* IPv6 Destination Address (accept) filter */
				if(filters.nacceptdst > MAX_ACCEPT_DST){
					puts("Too many IPv6 Destination Address (accept) filters.");
					exit(EXIT_FAILURE);
				}

				if((pref = strtok_r(optarg, "/", &lasts)) == NULL){
					printf("Error in IPv6 Destination Address (accept) filter number %u.\n", \
													filters.nacceptdst+1);
					exit(EXIT_FAILURE);
				}

				if ( inet_pton(AF_INET6, pref, &(filters.acceptdst[filters.nacceptdst])) <= 0){
					printf("Error in IPv6 Source Address (accept) filter number %u.\n", \
												    filters.nacceptdst+1);
					exit(EXIT_FAILURE);
				}

				if((charptr = strtok_r(NULL, " ", &lasts)) == NULL){
					filters.acceptdstlen[filters.nacceptdst] = 128;
				}
				else{
					filters.acceptdstlen[filters.nacceptdst] = atoi(charptr);
		
					if(filters.acceptdstlen[filters.nacceptdst] > 128){
						printf("Length error in IPv6 Source Address (accept) filter number %u.\n", \
													    filters.nacceptdst+1);
						exit(EXIT_FAILURE);
					}
				}
		
				sanitize_ipv6_prefix(&(filters.acceptdst[filters.nacceptdst]), filters.acceptdstlen[filters.nacceptdst]);
				(filters.nacceptdst)++;
				filters.acceptfilters_f=1;
				break;

			case 'B':	/* Link-layer Source Address (accept) filter */
				if(filters.nacceptlinksrc > MAX_ACCEPT_LINK_SRC){
					puts("Too many link-later Source Address (accept) filters.");
					exit(EXIT_FAILURE);
				}

				if(ether_pton(optarg, &(filters.acceptlinksrc[filters.nacceptlinksrc]), sizeof(struct ether_addr)) == 0){
					printf("Error in link-layer Source Address (accept) filter number %u.\n", \
											    filters.nacceptlinksrc+1);
					exit(EXIT_FAILURE);
				}
		
				(filters.nacceptlinksrc)++;
				filters.acceptfilters_f=1;
				break;

			case 'G':	/* Link Destination Address (accept) filter */
				if(filters.nacceptlinkdst > MAX_ACCEPT_LINK_DST){
					puts("Too many link-layer Destination Address (accept) filters.");
					exit(EXIT_FAILURE);
				}

				if(ether_pton(optarg, &(filters.acceptlinkdst[filters.nacceptlinkdst]), sizeof(struct ether_addr)) == 0){
					printf("Error in link-layer Destination Address (accept) filter number %u.\n",\
												    filters.nacceptlinkdst+1);
					exit(EXIT_FAILURE);
				}
		
				(filters.nacceptlinkdst)++;
				filters.acceptfilters_f=1;
				break;

			case 'w':	/* ND Target Address (block) filter */
				if(filters.nblocktarget > MAX_BLOCK_TARGET){
					puts("Too many Target Address (block) filters.");
					exit(EXIT_FAILURE);
				}
	    
				if((pref = strtok_r(optarg, "/", &lasts)) == NULL){
					printf("Error in Target Address (block) filter number %u.\n", filters.nblocktarget+1);
					exit(EXIT_FAILURE);
				}

				if ( inet_pton(AF_INET6, pref, &(filters.blocktarget[filters.nblocktarget])) <= 0){
					printf("Error in Target Address (block) filter number %u.\n", filters.nblocktarget+1);
					exit(EXIT_FAILURE);
				}

				if((charptr = strtok_r(NULL, " ", &lasts)) == NULL){
					filters.blocktargetlen[filters.nblocktarget] = 128;
				}
				else{
					filters.blocktargetlen[filters.nblocktarget] = atoi(charptr);
		
					if(filters.blocktargetlen[filters.nblocktarget]>128){
						printf("Length error in Target Address (block) filter number %u.\n", filters.nblocktarget+1);
						exit(EXIT_FAILURE);
					}
				}

				sanitize_ipv6_prefix(&(filters.blocktarget[filters.nblocktarget]), filters.blocktargetlen[filters.nblocktarget]);
				filters.nblocktarget++;
				break;

			case 'W':	/* ND Target Address (accept) filter */
				if(filters.naccepttarget >= MAX_ACCEPT_TARGET){
					puts("Too many Target Address (accept) filters.");
					exit(EXIT_FAILURE);
				}
	    
				if((pref = strtok_r(optarg, "/", &lasts)) == NULL){
					printf("Error in Target Address (accept) filter number %u.\n", filters.naccepttarget+1);
					exit(EXIT_FAILURE);
				}

				if ( inet_pton(AF_INET6, pref, &(filters.accepttarget[filters.naccepttarget])) <= 0){
					printf("Error in Target Address (accept) filter number %u.\n", filters.naccepttarget+1);
					exit(EXIT_FAILURE);
				}
		
				if((charptr = strtok_r(NULL, " ", &lasts)) == NULL){
					filters.accepttargetlen[filters.naccepttarget] = 128;
				}
				else{
					filters.accepttargetlen[filters.naccepttarget] = atoi(charptr);
		
					if(filters.accepttargetlen[filters.naccepttarget]>128){
						printf("Length error in Target Address (accept) filter number %u.\n", \
									    filters.naccepttarget+1);
						exit(EXIT_FAILURE);
					}
				}

				sanitize_ipv6_prefix(&(filters.accepttarget[filters.naccepttarget]), filters.accepttargetlen[filters.naccepttarget]);
				filters.naccepttarget++;
				filters.acceptfilters_f=1;
				break;

			case 'L':	/* "Listen mode */
				listen_f = 1;
				break;

			case 'T':	/* Flood targets */
				ntargets= atoi(optarg);
				if(ntargets == 0){
					puts("Invalid number of Target Addresses in option -T");
					exit(EXIT_FAILURE);
				}
		
				floodt_f= 1;
				break;

			case 'F':	/* Flood sources */
				nsources= atoi(optarg);
				if(nsources == 0){
					puts("Invalid number of sources in option -F");
					exit(EXIT_FAILURE);
				}
		
				floods_f= 1;
				break;

			case 'l':	/* "Loop mode */
				loop_f = 1;
				break;

			case 'z':	/* Sleep option */
				nsleep=atoi(optarg);
				if(nsleep==0){
					puts("Invalid number of seconds in '-z' option");
					exit(EXIT_FAILURE);
				}
	
				sleep_f=1;
				break;

			case 'v':	/* Be verbose */
				idata.verbose_f++;
				break;
		
			case 'h':	/* Help */
				print_help();
				exit(EXIT_FAILURE);
				break;

			default:
				usage();
				exit(EXIT_FAILURE);
				break;	
		} /* switch */
	} /* while(getopt) */

	if(geteuid()) {
		puts("na6 needs root privileges to run.");
		exit(EXIT_FAILURE);
	}

	if(!idata.iface_f){
		puts("Must specify the network interface with the -i option");
		exit(EXIT_FAILURE);
	}

	if(load_dst_and_pcap(&idata, LOAD_PCAP_ONLY) == FAILURE){
		puts("Error while learning Souce Address and Next Hop");
		exit(EXIT_FAILURE);
	}

	release_privileges();

	if(listen_f && loop_f){
		puts("'Error: listen' mode and 'loop' mode are incompatible");
		exit(EXIT_FAILURE);
	}

	if(listen_f && floodt_f){
		puts("Error: 'listen' mode and 'flood targets' are incompatible");
		exit(EXIT_FAILURE);
	}

	if(pcap_compile(idata.pfd, &pcap_filter, PCAP_ICMPV6_NS_FILTER, 0, PCAP_NETMASK_UNKNOWN) == -1){
		printf("pcap_compile(): %s", pcap_geterr(idata.pfd));
		exit(EXIT_FAILURE);
	}

   
	if(pcap_setfilter(idata.pfd, &pcap_filter) == -1){
		printf("pcap_setfilter(): %s", pcap_geterr(idata.pfd));
		exit(EXIT_FAILURE);
	}

	pcap_freecode(&pcap_filter);

	srandom(time(NULL));
    
	if(!(idata.srcaddr_f) && !floods_f){
		/* When randomizing a link-local IPv6 address, select addresses that belong to the
		   prefix fe80::/64 (that's what a link-local address looks-like in legitimate cases).
		   The KAME implementation discards addresses in which the second high-order 16 bits
		   (srcaddr.s6_addr16[1] in our case) are not zero.
		 */  

		if(idata.ip6_local_flag){
			idata.srcaddr= idata.ip6_local;
		}
		else{
			if ( inet_pton(AF_INET6, "fe80::", &(idata.srcaddr)) <= 0){
				puts("inet_pton(): Error when converting address");
				exit(EXIT_FAILURE);
			}

			randomize_ipv6_addr(&(idata.srcaddr), &(idata.srcaddr), 64);
		}
	}

	/*
	   If the flood option ("-F") has been specified, but no prefix has been specified,
	   select the random Source Addresses from the link-local unicast prefix (fe80::/64).
	 */
	if(floods_f && !idata.srcprefix_f){
		if ( inet_pton(AF_INET6, "fe80::", &(idata.srcaddr)) <= 0){
			puts("inet_pton(): Error when converting address");
			exit(EXIT_FAILURE);
		}

		randomize_ipv6_addr(&(idata.srcaddr), &(idata.srcaddr), 64);
	
		idata.srcpreflen=64;
	}

	if(!idata.dstaddr_f){		/* Destination Address defaults to all-nodes (ff02::1) */
		if( inet_pton(AF_INET6, ALL_NODES_MULTICAST_ADDR, &(idata.dstaddr)) <= 0){
			puts("inet_pton(): Error converting all-nodes multicast address");
			exit(EXIT_FAILURE);
		}
	}

	if(!idata.hdstaddr_f)		/* Destination link-layer address defaults to all-nodes */
		if(ether_pton(ETHER_ALLNODES_LINK_ADDR, &(idata.hdstaddr), sizeof(idata.hdstaddr)) == 0){
			puts("ether_pton(): Error converting all-nodes multicast address");
			exit(EXIT_FAILURE);
		}
    
	if(tllaopt_f && !tllaopta_f){	/* The value of the target link-layer address      */
		linkaddr[0] = idata.hsrcaddr;		/* option defaults to the Ethernet Source Address  */
		nlinkaddr++;
	}


	/*
	   If the flood target option ("-T") was specified, but no prefix was specified,
	   select the random Target Addresses from the link-local unicast prefix (fe80::/64).
	 */
	if(floodt_f && !targetprefix_f){
		if ( inet_pton(AF_INET6, "fe80::", &targetaddr) <= 0){
			puts("inet_pton(): Error when converting address");
			exit(EXIT_FAILURE);
		}

		randomize_ipv6_addr(&targetaddr, &targetaddr, 64);
		targetpreflen=64;
	}

	if(!floods_f)
		nsources=1;

	if(!floodt_f)
		ntargets=1;

	if(!sleep_f)
		nsleep=1;

	if(!idata.fragh_f && dstoptuhdr_f){
		puts("Dst. Options Header (Unfragmentable Part) set, but Fragmentation not specified");
		exit(EXIT_FAILURE);
	}
    
	if(idata.verbose_f){
		print_attack_info(&idata);
	}

	/* Set initial contents of the attack packet */
	init_packet_data(&idata);
    
	/* Fire a Neighbor Advertisement if a IPv6 Destination Address or an Ethernet
	 * Destination Address were specified
	 */
	if((idata.dstaddr_f || idata.hdstaddr_f) && (targetaddr_f || floodt_f)){
		if(send_packet(&idata, NULL, NULL) == FAILURE){
			puts("Error while sending packet");
			exit(EXIT_FAILURE);
		}

		if(idata.verbose_f)    
			puts("Initial attack packet(s) sent successfully.");

		if(loop_f){
			if(idata.verbose_f)
				printf("Now sending Neighbor Advertisements every %u second%s...\n", nsleep, \
											((nsleep>1)?"s":""));
			while(loop_f){
				sleep(nsleep);
				if(send_packet(&idata, NULL, NULL) == FAILURE){
					puts("Error while sending packet");
					exit(EXIT_FAILURE);
				}
	 		}

			exit(EXIT_SUCCESS);
		}
	}

	if(listen_f){
		FD_ZERO(&sset);
		FD_SET(idata.fd, &sset);

		if(idata.verbose_f){
			print_filters(&idata, &filters);
			puts("Listening to incoming ICMPv6 Neighbor Solicitation messages...");
		}

		while(listen_f){
			rset= sset;

#if defined(sun) || defined(__sun) || defined(__linux__)
			timeout.tv_usec=1000;
			timeout.tv_sec= 0;
			if((sel=select(idata.fd+1, &rset, NULL, NULL, &timeout)) == -1){
#else
			if((sel=select(idata.fd+1, &rset, NULL, NULL, NULL)) == -1){
#endif
				if(errno == EINTR){
					continue;
				}
				else{
					puts("Error in select()");
					exit(EXIT_FAILURE);
				}
			}

#if defined(sun) || defined(__sun) || defined(__linux__)
			if(TRUE){
#else
			if(sel && FD_ISSET(idata.fd, &rset)){
#endif
				/* Read a Neighbor Solicitation message */
				if((r=pcap_next_ex(idata.pfd, &pkthdr, &pktdata)) == -1){
					printf("pcap_next_ex(): %s", pcap_geterr(idata.pfd));
					exit(EXIT_FAILURE);
				}
				else if(r == 1 && pktdata != NULL){
					/* XXX Code assumes no IPv6 Extension Headers */
					pkt_ether = (struct ether_header *) pktdata;
					pkt_ipv6 = (struct ip6_hdr *)((char *) pkt_ether + idata.linkhsize);
					pkt_ns = (struct nd_neighbor_solicit *) ((char *) pkt_ipv6 + MIN_IPV6_HLEN);
					pkt_icmp6= (struct icmp6_hdr *) pkt_ns;

					/* XXX This should probably be removed when pcap filter problem is solved */
					if(pkt_ipv6->ip6_nxt != IPPROTO_ICMPV6 || pkt_icmp6->icmp6_type != ND_NEIGHBOR_SOLICIT || \
						pkt_icmp6->icmp6_code != 0)
						continue;

					accepted_f=0;

					if(idata.type == DLT_EN10MB && !(idata.flags & IFACE_LOOPBACK)){
						if(filters.nblocklinksrc){
							if(match_ether(filters.blocklinksrc, filters.nblocklinksrc, &(pkt_ether->src))){
								if(idata.verbose_f>1)
									print_filter_result(&idata, pktdata, BLOCKED);
		
								continue;
							}
						}

						if(filters.nblocklinkdst){
							if(match_ether(filters.blocklinkdst, filters.nblocklinkdst, &(pkt_ether->dst))){
								if(idata.verbose_f>1)
									print_filter_result(&idata, pktdata, BLOCKED);
		
								continue;
							}
						}
					}
	
					if(filters.nblocksrc){
						if(match_ipv6(filters.blocksrc, filters.blocksrclen, filters.nblocksrc, &(pkt_ipv6->ip6_src))){
							if(idata.verbose_f>1)
								print_filter_result(&idata, pktdata, BLOCKED);
		
							continue;
						}
					}
	
					if(filters.nblockdst){
						if(match_ipv6(filters.blockdst, filters.blockdstlen, filters.nblockdst, &(pkt_ipv6->ip6_dst))){
							if(idata.verbose_f>1)
								print_filter_result(&idata, pktdata, BLOCKED);
		
							continue;
						}
					}

					if(filters.nblocktarget){
						if(match_ipv6(filters.blocktarget, filters.blocktargetlen, filters.nblocktarget, &(pkt_ns->nd_ns_target))){
							if(idata.verbose_f>1)
								print_filter_result(&idata, pktdata, BLOCKED);
		
							continue;
						}
					}

					if(idata.type == DLT_EN10MB && !(idata.flags & IFACE_LOOPBACK)){	
						if(filters.nacceptlinksrc){
							if(match_ether(filters.acceptlinksrc, filters.nacceptlinksrc, &(pkt_ether->src)))
								accepted_f=1;
						}

						if(filters.nacceptlinkdst && !accepted_f){
							if(match_ether(filters.acceptlinkdst, filters.nacceptlinkdst, &(pkt_ether->dst)))
								accepted_f= 1;
						}
					}

					if(filters.nacceptsrc && !accepted_f){
						if(match_ipv6(filters.acceptsrc, filters.acceptsrclen, filters.nacceptsrc, &(pkt_ipv6->ip6_src)))
							accepted_f= 1;
					}

					if(filters.nacceptdst && !accepted_f){
						if(match_ipv6(filters.acceptdst, filters.acceptdstlen, filters.nacceptdst, &(pkt_ipv6->ip6_dst)))
							accepted_f=1;
					}

					if(filters.naccepttarget && !accepted_f){
						if(match_ipv6(filters.accepttarget, filters.accepttargetlen, filters.naccepttarget, &(pkt_ns->nd_ns_target)))
							accepted_f=1;
					}
	
					if(filters.acceptfilters_f && !accepted_f){
						if(idata.verbose_f>1)
							print_filter_result(&idata, pktdata, BLOCKED);

						continue;
					}

					if(idata.verbose_f)
						print_filter_result(&idata, pktdata, ACCEPTED);

					/* Send a Neighbor Advertisement */
					if(send_packet(&idata, pkthdr, pktdata) == FAILURE){
						puts("Error while sending packet");
						exit(EXIT_FAILURE);
					}
				}
			}
		}
    
		exit(EXIT_SUCCESS);
	}
    

	if(!((idata.dstaddr_f || idata.hdstaddr_f) && (targetaddr_f || floodt_f)) && !listen_f){
		puts("Error: Nothing to send! (Destination Address or ND Target Address missing?)");
		exit(EXIT_FAILURE);
	}

	exit(EXIT_SUCCESS);
}



/*
 * Function: init_packet_data()
 *
 * Initialize the contents of the attack packet (Ethernet header, IPv6 Header, and ICMPv6 header)
 * that are expected to remain constant for the specified attack.
 */
void init_packet_data(struct iface_data *idata){
	struct dlt_null *dlt_null;
	ethernet= (struct ether_header *) buffer;
	dlt_null= (struct dlt_null *) buffer;
	v6buffer = buffer + idata->linkhsize;
	ipv6 = (struct ip6_hdr *) v6buffer;

	if(idata->type == DLT_EN10MB){
		ethernet->ether_type = htons(ETHERTYPE_IPV6);

	if(!(idata->flags & IFACE_LOOPBACK)){
			ethernet->src = idata->hsrcaddr;
			ethernet->dst = idata->hdstaddr;
		}
	}
	else if(idata->type == DLT_NULL){
		dlt_null->family= PF_INET6;
	}
#if defined (__OpenBSD__)
	else if(idata->type == DLT_LOOP){
		dlt_null->family= htonl(PF_INET6);
	}
#endif

	ipv6->ip6_flow=0;
	ipv6->ip6_vfc= 0x60;
	ipv6->ip6_hlim= hoplimit;
	ipv6->ip6_src= idata->srcaddr;
	ipv6->ip6_dst= idata->dstaddr;

	prev_nh = (unsigned char *) &(ipv6->ip6_nxt);

	ptr = (unsigned char *) v6buffer + MIN_IPV6_HLEN;
    
	if(hbhopthdr_f){
		hbhopthdrs=0;
	
		while(hbhopthdrs < nhbhopthdr){
			if((ptr+ hbhopthdrlen[hbhopthdrs]) > (v6buffer+ idata->mtu)){
				puts("Packet too large while processing HBH Opt. Header");
				exit(EXIT_FAILURE);
			}
	    
			*prev_nh = IPPROTO_HOPOPTS;
			prev_nh = ptr;
			memcpy(ptr, hbhopthdr[hbhopthdrs], hbhopthdrlen[hbhopthdrs]);
			ptr = ptr + hbhopthdrlen[hbhopthdrs];
			hbhopthdrs++;
		}
	}

	if(dstoptuhdr_f){
		dstoptuhdrs=0;
	
		while(dstoptuhdrs < ndstoptuhdr){
			if((ptr+ dstoptuhdrlen[dstoptuhdrs]) > (v6buffer+ idata->mtu)){
				puts("Packet too large while processing Dest. Opt. Header (Unfrag. Part)");
				exit(EXIT_FAILURE);
			}

			*prev_nh = IPPROTO_DSTOPTS;
			prev_nh = ptr;
			memcpy(ptr, dstoptuhdr[dstoptuhdrs], dstoptuhdrlen[dstoptuhdrs]);
			ptr = ptr + dstoptuhdrlen[dstoptuhdrs];
			dstoptuhdrs++;
		}
	}

	/* Everything that follows is the Fragmentable Part of the packet */
	fragpart = ptr;

	if(idata->fragh_f){
		/* Check that we are able to send the Unfragmentable Part, together with a 
		   Fragment Header and a chunk data over our link layer
		 */
		if( (fragpart+sizeof(fraghdr)+nfrags) > (v6buffer+idata->mtu)){
			printf("Unfragmentable part too large for current MTU (%u bytes)\n", idata->mtu);
			exit(EXIT_FAILURE);
		}

		/* We prepare a separete Fragment Header, but we do not include it in the packet to be sent.
		   This Fragment Header will be used (an assembled with the rest of the packet by the 
		   send_packet() function.
		*/
		memset(&fraghdr, 0, FRAG_HDR_SIZE);
		*prev_nh = IPPROTO_FRAGMENT;
		prev_nh = (unsigned char *) &fraghdr;
	}

	if(dstopthdr_f){
		dstopthdrs=0;
	
		while(dstopthdrs < ndstopthdr){
			if((ptr+ dstopthdrlen[dstopthdrs]) > (v6buffer+idata->max_packet_size)){
			puts("Packet too large while processing Dest. Opt. Header (should be using the Frag. option?)");
			exit(EXIT_FAILURE);
			}
    
			*prev_nh = IPPROTO_DSTOPTS;
			prev_nh = ptr;
			memcpy(ptr, dstopthdr[dstopthdrs], dstopthdrlen[dstopthdrs]);
			ptr = ptr + dstopthdrlen[dstopthdrs];
			dstopthdrs++;
		}
	}


	*prev_nh = IPPROTO_ICMPV6;

	if( (ptr+sizeof(struct nd_neighbor_advert)) > (v6buffer+idata->max_packet_size)){
		puts("Packet too large while inserting Neighbor Advertisement header (should be using Frag. option?)");
		exit(EXIT_FAILURE);
	}

	na= (struct nd_neighbor_advert *) ptr;

	na->nd_na_type = ND_NEIGHBOR_ADVERT;
	na->nd_na_code = 0;
	na->nd_na_flags_reserved = router_f | solicited_f | override_f;
	na->nd_na_target = targetaddr;
    
	ptr += sizeof(struct nd_neighbor_advert);

	if(tllaopt_f && nlinkaddr==1){
		if( (ptr+sizeof(struct nd_opt_tlla)) <= (v6buffer+idata->max_packet_size) ){
			tllaopt = (struct nd_opt_tlla *) ptr;
			tllaopt->type= ND_OPT_TARGET_LINKADDR;
			tllaopt->length= TLLA_OPT_LEN;
			memcpy(tllaopt->address, linkaddr[0].a, ETH_ALEN);
			ptr += sizeof(struct nd_opt_tlla);
		}
		else{
			puts("Packet Too Large while processing target link-layer address option");
			exit(EXIT_FAILURE);
		}
	}

	startofprefixes=ptr;
}



/*
 * Function: send_packet()
 *
 * Initialize the remaining fields of the Neighbor Advertisement Message, and
 * send the attack packet(s).
 */
int send_packet(struct iface_data *idata, struct pcap_pkthdr *pkthdr, const u_char *pktdata){
	if(pktdata == NULL){
		sources=0;
	}
	else{   /* Sending a response to a Neighbor Solicitation message */
		pkt_ether = (struct ether_header *) pktdata;
		pkt_ipv6 = (struct ip6_hdr *)((char *) pkt_ether + idata->linkhsize);
		pkt_ns = (struct nd_neighbor_solicit *) ((char *) pkt_ipv6 + MIN_IPV6_HLEN);
	
		/* If the IPv6 Source Address of the incoming Neighbor Solicitation is the unspecified 
		   address (::), the Neighbor Advertisement must be directed to the IPv6 all-nodes 
		   multicast address (and the Ethernet Destination address should be 33:33:33:00:00:01). 
		   Otherwise, the Neighbor Advertisement is sent to the IPv6 Source Address (and 
		   Ethernet Source Address) of the incoming Neighbor Solicitation message
		 */
		pkt_ipv6addr = &(pkt_ipv6->ip6_src);

		na->nd_na_flags_reserved = router_f | solicited_f | override_f;

		if(IN6_IS_ADDR_UNSPECIFIED(pkt_ipv6addr)){
			if ( inet_pton(AF_INET6, ALL_NODES_MULTICAST_ADDR, &(ipv6->ip6_dst)) <= 0){
				puts("inetr_pton(): Error converting all-nodes multicast address");
				return(FAILURE);
			}

			if(ether_pton(ETHER_ALLNODES_LINK_ADDR, &(ethernet->dst), ETHER_ADDR_LEN) == 0){
				puts("ether_pton(): Error converting all-nodes link-local address");
				return(FAILURE);
			}
		}
		else{
			ipv6->ip6_dst = pkt_ipv6->ip6_src;
			ethernet->dst = pkt_ether->src;

			/* 
			   Set the "Solicited" flag if NS was sent from an address other than the unspecified
			   address (i.e., the response will be unicast). 
			 */ 

			na->nd_na_flags_reserved = na->nd_na_flags_reserved | ND_NA_FLAG_SOLICITED;
		}

		pkt_ipv6addr = &(pkt_ipv6->ip6_dst);

		/* 
		   If the Neighbor Solicitation message was directed to a unicast address (unlikely), the
		   IPv6 Source Address and the Ethernet Source Address of the Neighbor Advertisement are set
		   to the IPv6 Destination Address and the Ethernet Destination Address	of the incoming
		   Neighbor Solicitation, respectively. Otherwise, the IPv6 Source Address is set to the
		   ND Target Address (unless a specific IPv6 Source Address was specified with the "-s"
		   option), and the Ethernet is set to that specified by the "-S" option (or randomized).
		 */
		if(IN6_IS_ADDR_MULTICAST(pkt_ipv6addr)){
			if( !idata->srcaddr_f && IN6_IS_ADDR_LINKLOCAL(&(pkt_ns->nd_ns_target)) )
				ipv6->ip6_src = pkt_ns->nd_ns_target;
			else
				ipv6->ip6_src = idata->srcaddr;

			ethernet->src = idata->hsrcaddr;
			sources=0;
			multicastdst_f=1;
		}
		else{
			ipv6->ip6_src = pkt_ipv6->ip6_dst;
			ethernet->src = pkt_ether->dst;
			sources=nsources;
			multicastdst_f=0;
		}

		na->nd_na_target= pkt_ns->nd_ns_target;
	}


	do{
		if(floods_f && (pktdata==NULL || (pktdata != NULL && multicastdst_f))){
			/* 
			   Randomizing the IPv6 Source address based on the prefix specified by 
			   "srcaddr" and prefix length.
			 */  
			randomize_ipv6_addr(&(ipv6->ip6_src), &(idata->srcaddr), idata->srcpreflen);

			if(!idata->hsrcaddr_f){
				randomize_ether_addr(&(ethernet->src));
			}
	    
			if(tllaopt_f && !tllaopta_f){
				memcpy(tllaopt->address, ethernet->src.a, ETH_ALEN);
			}
		}

		targets=0;

		do{
			if(floodt_f){
				/* 
				   Randomizing the ND Target Address based on the prefix specified by "targetaddr" 
				   and targetpreflen.
				 */  
				randomize_ipv6_addr(&(na->nd_na_target), &targetaddr, targetpreflen);
			}

			/*
			 * If a single target link-layer address option is to be included, it is included
			 * by init_packet_data()
			 */
			if(nlinkaddr==1)
				linkaddrs=1;
			else
				linkaddrs=0;

			do{
				newdata_f=0;
				ptr=startofprefixes;

				while(linkaddrs<nlinkaddr && ((ptr+sizeof(struct nd_opt_tlla))-v6buffer)<=idata->max_packet_size){
					tllaopt = (struct nd_opt_tlla *) ptr;
					tllaopt->type= ND_OPT_TARGET_LINKADDR;
					tllaopt->length= TLLA_OPT_LEN;
					memcpy(tllaopt->address, linkaddr[linkaddrs].a, ETH_ALEN);
					ptr += sizeof(struct nd_opt_tlla);
					linkaddrs++;
					newdata_f=1;
				}

				na->nd_na_cksum = 0;
				na->nd_na_cksum = in_chksum(v6buffer, na, ptr-((unsigned char *)na), IPPROTO_ICMPV6);


				if(!idata->fragh_f){
					ipv6->ip6_plen = htons((ptr - v6buffer) - MIN_IPV6_HLEN);

					if((nw=pcap_inject(idata->pfd, buffer, ptr - buffer)) == -1){
						printf("pcap_inject(): %s\n", pcap_geterr(idata->pfd));
						return(FAILURE);
					}

					if(nw != (ptr-buffer)){
						printf("pcap_inject(): only wrote %lu bytes (rather than %lu bytes)\n", (LUI) nw, \
																					(LUI) (ptr-buffer));
						return(FAILURE);
					}
				}
				else{
					ptrend= ptr;
					ptr= fragpart;
					fptr = fragbuffer;
					fipv6 = (struct ip6_hdr *) (fragbuffer + ETHER_HDR_LEN);
					fptrend = fptr + ETHER_HDR_LEN+MIN_IPV6_HLEN+MAX_IPV6_PAYLOAD;
					memcpy(fptr, buffer, fragpart-buffer);
					fptr = fptr + (fragpart-buffer);

					if( (fptr+FRAG_HDR_SIZE)> fptrend){
						puts("Unfragmentable Part is Too Large");
						return(FAILURE);
					}

					memcpy(fptr, (char *) &fraghdr, FRAG_HDR_SIZE);
					fh= (struct ip6_frag *) fptr;
					fh->ip6f_ident=random();
					startoffragment = fptr + FRAG_HDR_SIZE;

					/*
					 * Check that the selected fragment size is not larger than the largest 
					 * fragment size that can be sent
					 */
					if(nfrags <= (fptrend - fptr))
						fragsize=nfrags;
					else
						fragsize= (fptrend-fptr) & IP6F_OFF_MASK;

					m=IP6F_MORE_FRAG;

					while((ptr< ptrend) && m==IP6F_MORE_FRAG){
						fptr= startoffragment;

						if( (ptrend-ptr) <= fragsize){
							fragsize= ptrend-ptr;
							m=0;
						}

						memcpy(fptr, ptr, fragsize);
						fh->ip6f_offlg = (htons(ptr-fragpart) & IP6F_OFF_MASK) | m;
						ptr+=fragsize;
						fptr+=fragsize;

						fipv6->ip6_plen = htons((fptr - fragbuffer) - MIN_IPV6_HLEN - ETHER_HDR_LEN);
		
						if((nw=pcap_inject(idata->pfd, fragbuffer, fptr - fragbuffer)) == -1){
							printf("pcap_inject(): %s\n", pcap_geterr(idata->pfd));
							return(FAILURE);
						}

						if(nw != (fptr- fragbuffer)){
							printf("pcap_inject(): only wrote %lu bytes (rather than %lu bytes)\n"\
													, (LUI) nw, (LUI) (ptr-buffer));
							return(FAILURE);
						}
					}
				}
			}while(linkaddrs<nlinkaddr && newdata_f);

			targets++;

		}while(targets<ntargets);

		sources++;
	}while(sources<nsources);

	return(SUCCESS);
}



/*
 * Function: usage()
 *
 * Prints the syntax of the na6 tool
 */
void usage(void){
    puts("usage: na6 -i INTERFACE [-s SRC_ADDR[/LEN]] [-d DST_ADDR] [-S LINK_SRC_ADDR] "
	 "[-y FRAG_SIZE] [-u DST_OPT_HDR_SIZE] [-U DST_OPT_U_HDR_SIZE] [-H HBH_OPT_HDR_SIZE] "
	 "[-D LINK-DST-ADDR] [-t TARGET_ADDR[/LEN]] [-r] [-c] [-o] [-E LINK_ADDR] [-e] "
	 "[-j PREFIX[/LEN]] [-k PREFIX[/LEN]] [-J LINK_ADDR] [-K LINK_ADDR] [-w PREFIX[/LEN]] "
	 "[-b PREFIX[/LEN]] [-g PREFIX[/LEN]] [-B LINK_ADDR] [-G LINK_ADDR] [-W PREFIX[/LEN]] "
	 "[-F N_SOURCES] [-T N_TARGETS] [-L | -l] [-z] [-v] [-V] [-h]");
}


/*
 * Function: print_help()
 *
 * Prints help information for the na6 tool
 */
void print_help(void){
	puts(SI6_TOOLKIT);
	puts("na6: Security Assessment tool for attack vectors based on NA messages\n");
	usage();
    
    puts("\nOPTIONS:\n"
	"  --interface, -i            Network interface\n"
	"  --src-address, -s          IPv6 Source Address\n"
	"  --dst-address, -d          IPv6 Destination Address\n"
	"  --frag-hdr. -y             Fragment Header\n"
	"  --dst-opt-hdr, -u          Destination Options Header (Fragmentable Part)\n"
	"  --dst-opt-u-hdr, -U        Destination Options Header (Unfragmentable Part)\n"
	"  --hbh-opt-hdr, -H          Hop by Hop Options Header\n"
	"  --link-src-address, -S     Link-layer Destination Address\n"
	"  --link-dst-address, -D     Link-layer Source Address\n"
	"  --target, -t               ND IPv6 Target Address\n"
	"  --target-lla-opt, -E       Source link-layer address option\n"
	"  --add-tlla-opt, -e         Add Source link-layer address option\n"
	"  --router, -r               Set the 'Router Flag'\n"
	"  --solicited, -c            Set the 'Solicited' flag\n"
	"  --override, -o             Set the 'Override' flag\n"
	"  --block-src, -j            Block IPv6 Source Address prefix\n"
	"  --block-dst, -k            Block IPv6 Destination Address prefix\n"
	"  --block-link-src, -J       Block Ethernet Source Address\n"
	"  --block-link-dst, -K       Block Ethernet Destination Address\n"
	"  --block-target, -w         Block ND Target IPv6 prefix\n"
	"  --accept-src, -b           Accept IPv6 Source Addres prefix\n"
	"  --accept-dst, -g           Accept IPv6 Destination Addres prefix\n"
	"  --accept-link-src, -B      Accept Ethernet Source Address\n"
	"  --accept-link-dst, -G      Accept Ethernet Destination Address\n"
	"  --accept-target, -W        Accept ND Target IPv6 prefix\n"
	"  --flood-targets, -T        Flood with NA's for multiple Target Addresses\n"
	"  --flood-sources, -F        Number of Source Addresses to forge randomly\n"
	"  --listen, -L               Listen to Neighbor Solicitation messages\n"
	"  --loop, -l                 Send periodic Neighbor Advertisements\n"
	"  --sleep, -z                Pause between sending NA messages\n"
	"  --help, -h                 Print help for the na6 tool\n"
	"  --verbose, -v              Be verbose\n"
	"\n"
	"Programmed by Fernando Gont for SI6 Networks <http://www.si6networks.com>\n"
	"Please send any bug reports to <*****@*****.**>\n"
	);
}
Exemplo n.º 27
0
int main(int argc, char **argv)
{
    int ret;
    AVPacket packet0, packet;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    if (!frame || !filt_frame) {
        perror("Could not allocate frame");
        exit(1);
    }
    if (argc != 2) {
        fprintf(stderr, "Usage: %s file | %s\n", argv[0], player);
        exit(1);
    }

    avcodec_register_all();
    av_register_all();
    avfilter_register_all();

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;

    /* read all packets */
    packet0.data = NULL;
    packet.data = NULL;
    while (1) {
        if (!packet0.data) {
            if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
                break;
            packet0 = packet;
        }

        if (packet.stream_index == audio_stream_index) {
            got_frame = 0;
            ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
                continue;
            }
            packet.size -= ret;
            packet.data += ret;

            if (got_frame) {
                /* push the audio data from decoded frame into the filtergraph */
                if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
                    break;
                }

                /* pull filtered audio from the filtergraph */
                while (1) {
                    ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;
                    print_frame(filt_frame);
                    av_frame_unref(filt_frame);
                }
            }

            if (packet.size <= 0)
                av_free_packet(&packet0);
        } else {
            /* discard non-wanted packets */
            av_free_packet(&packet0);
        }
    }
end:
    avfilter_graph_free(&filter_graph);
    avcodec_close(dec_ctx);
    avformat_close_input(&fmt_ctx);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);

    if (ret < 0 && ret != AVERROR_EOF) {
        fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
        exit(1);
    }

    exit(0);
}
Exemplo n.º 28
0
int main(int argc, char **argv)
{
    int ret;
    AVPacket packet;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();

    if (!frame || !filt_frame) {
        perror("Could not allocate frame");
        exit(1);
    }
    if (argc != 2) {
        fprintf(stderr, "Usage: %s file | %s\n", argv[0], player);
        exit(1);
    }

    if ((ret = open_input_file(argv[1])) < 0)
        goto end;
    if ((ret = init_filters(filter_descr)) < 0)
        goto end;

    /* read all packets */
    while (1) {
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;

        if (packet.stream_index == audio_stream_index) {
            ret = avcodec_send_packet(dec_ctx, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
                break;
            }

            while (ret >= 0) {
                ret = avcodec_receive_frame(dec_ctx, frame);
                if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
                    break;
                } else if (ret < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
                    goto end;
                }

                if (ret >= 0) {
                    /* push the audio data from decoded frame into the filtergraph */
                    if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
                        av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
                        break;
                    }

                    /* pull filtered audio from the filtergraph */
                    while (1) {
                        ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                            break;
                        if (ret < 0)
                            goto end;
                        print_frame(filt_frame);
                        av_frame_unref(filt_frame);
                    }
                    av_frame_unref(frame);
                }
            }
        }
        av_packet_unref(&packet);
    }
end:
    avfilter_graph_free(&filter_graph);
    avcodec_free_context(&dec_ctx);
    avformat_close_input(&fmt_ctx);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);

    if (ret < 0 && ret != AVERROR_EOF) {
        fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
        exit(1);
    }

    exit(0);
}
Exemplo n.º 29
0
EXPORT void *init_capture(const char *in, const char *out, struct inputCfg *cfg)
{

	int ret = 0;
	// structure with ffmpeg variables
	struct liveStream *ctx = NULL;
	AVStream *stream = NULL;

	// allocation of Live Stream structure
	ctx = malloc(sizeof(struct liveStream));
	if(ctx == NULL)
	{
		fprintf(stderr,"Error in liveStream struct alloc\n");
		return NULL;
	}
	memset(ctx, 0, sizeof(*ctx));

	init_ffmpeg();

	ret = configure_input(ctx, in, cfg);
	if(ret < 0)
	{
		av_log(NULL,AV_LOG_ERROR,"unable to configure input\n");
		free(ctx);
		return  NULL;
	}

	stream = ctx->inputs[0].st;
	/** Initalize framerate coming from webcam */
	if(stream->avg_frame_rate.num && stream->avg_frame_rate.den)
	{
		ctx->video_avg_frame_rate.num = stream->avg_frame_rate.num;
		ctx->video_avg_frame_rate.den = stream->avg_frame_rate.den;
	}
	else if(stream->r_frame_rate.num && stream->r_frame_rate.den )
	{
		ctx->video_avg_frame_rate.num = stream->r_frame_rate.num;
		ctx->video_avg_frame_rate.den = stream->r_frame_rate.den;
	}
	else
	{
		fprintf(stderr, "Unable to take out fps from webcam assuming 30fps\n");
		ctx->video_avg_frame_rate.num = 30;
		ctx->video_avg_frame_rate.den = 1;

	}
	ctx->have_filter = 1;

	ret = init_filters(ctx);
	if(ret < 0)
	{
		fprintf(stderr,"unable to initialize filter\n");
		goto end;
	}

	ret = init_encoder(ctx, out);
	if(ret < 0)
	{
		printf("Error in encoder init for %s\n", out);
		ret =-1;
		goto end;
	}

	ctx->OutFrame = av_frame_alloc();
end:
	if(ret < 0)
	{
		stop_capture((void*)ctx);
		return NULL;
	}
	return ctx;
}
Exemplo n.º 30
0
void init_stuff()
{
	int i;
	int seed;

	chdir(DATA_DIR);
	
#ifndef WINDOWS
	setlocale(LC_NUMERIC,"en_US");
#endif
	init_translatables();

	//create_error_mutex();
	init_globals();
	init_crc_tables();
	init_zip_archives();
	cache_system_init(MAX_CACHE_SYSTEM);
	init_texture_cache();

	init_vars();
	
	read_config();

	file_check_datadir();

#ifdef LOAD_XML
	//Well, the current version of the map editor doesn't support having a datadir - will add that later ;-)
	load_translatables();
#endif

#ifdef LINUX
#ifdef GTK2
	init_filters();
#else
	file_selector = create_fileselection();
#endif
#endif	//LINUX

	init_gl();

	window_resize();
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
//	glDepthFunc(GL_LEQUAL);
    glEnable(GL_TEXTURE_2D);
	glShadeModel(GL_SMOOTH);
	glFrontFace(GL_CCW);
	glCullFace(GL_BACK);
	glEnable(GL_NORMALIZE);
	glClearColor( 0.0, 0.0, 0.0, 0.0 );
	glClearStencil(0);

	seed = time (NULL);
  	srand (seed);

	init_texture_cache();
	init_particles ();
	init_e3d_cache();
	init_2d_obj_cache();

	for(i=0; i<256; i++)
        tile_list[i]=0;

	for (i = 0; i < MAX_LIGHTS; i++)
		lights_list[i] = NULL;

	new_map(256,256);
	load_all_tiles();

	//lights setup
	build_global_light_table();
	build_sun_pos_table();
	reset_material();
	init_lights();
	//disable_local_lights();
	//clear_error_log();

	// Setup the new eye candy system
#ifdef	EYE_CANDY
	ec_init();
#endif	//EYE_CANDY

	init_gl_extensions();

	if(have_multitexture)
#ifdef	NEW_TEXTURES
		ground_detail_text = load_texture_cached("./textures/ground_detail.bmp", tt_mesh);
#else	/* NEW_TEXTURES */
		ground_detail_text = load_texture_cache ("./textures/ground_detail.bmp",255);
#endif	/* NEW_TEXTURES */

	//load the fonts texture
	init_fonts();
#ifdef	NEW_TEXTURES
	icons_text=load_texture_cached("./textures/gamebuttons.bmp", tt_gui);
	buttons_text=load_texture_cached("./textures/buttons.bmp", tt_gui);
#else	/* NEW_TEXTURES */
	icons_text=load_texture_cache("./textures/gamebuttons.bmp",0);
	buttons_text=load_texture_cache("./textures/buttons.bmp",0);
#endif	/* NEW_TEXTURES */
	//get the application home dir

	have_multitexture=0;//debug only

#ifndef LINUX
	GetCurrentDirectory(sizeof(exec_path),exec_path);
#else
	exec_path[0]='.';exec_path[1]='/';exec_path[2]=0;
#endif
	init_browser();

    if(SDL_InitSubSystem(SDL_INIT_TIMER)<0)
    { 
        char str[120];
        snprintf(str, sizeof(str), "Couldn't initialize the timer: %s\n", SDL_GetError());
        log_error(__FILE__, __LINE__, str);
        SDL_Quit();
	    exit(1);
    }

	SDL_SetTimer (1000/(18*4), my_timer);

	SDL_EnableUNICODE(1);

    //we might want to do this later.

	// creating windows
	display_browser();
	toggle_window(browser_win);

	display_o3dow();
	toggle_window(o3dow_win);

	display_replace_window();
	toggle_window(replace_window_win);

	display_edit_window();
	toggle_window(edit_window_win);

	create_particles_window ();
}