void SyntaxLineEdit::checkDisplayFilter(QString filter)
{
    if (filter.isEmpty()) {
        setSyntaxState(SyntaxLineEdit::Empty);
        return;
    }

    dfilter_t *dfp = NULL;
    gchar *err_msg;
    if (dfilter_compile(filter.toUtf8().constData(), &dfp, &err_msg)) {
        GPtrArray *depr = NULL;
        if (dfp) {
            depr = dfilter_deprecated_tokens(dfp);
        }
        if (depr) {
            // You keep using that word. I do not think it means what you think it means.
            setSyntaxState(SyntaxLineEdit::Deprecated);
            /*
             * We're being lazy and only printing the first "problem" token.
             * Would it be better to print all of them?
             */
            syntax_error_message_ = tr("\"%1\" may have unexpected results (see the User's Guide)")
                    .arg((const char *) g_ptr_array_index(depr, 0));
        } else {
            setSyntaxState(SyntaxLineEdit::Valid);
        }
    } else {
        setSyntaxState(SyntaxLineEdit::Invalid);
        syntax_error_message_ = QString::fromUtf8(err_msg);
        g_free(err_msg);
    }
    dfilter_free(dfp);
}
Example #2
0
void
build_column_format_array(column_info *cinfo, const gint num_cols, const gboolean reset_fences)
{
  int i;

  /* Build the column format array */
  col_setup(cinfo, num_cols);

  for (i = 0; i < cinfo->num_cols; i++) {
    cinfo->col_fmt[i] = get_column_format(i);
    cinfo->col_title[i] = g_strdup(get_column_title(i));

    if (cinfo->col_fmt[i] == COL_CUSTOM) {
      cinfo->col_custom_field[i] = g_strdup(get_column_custom_field(i));
      if(!dfilter_compile(cinfo->col_custom_field[i], &cinfo->col_custom_dfilter[i])) {
        /* XXX: Should we issue a warning? */
        g_free(cinfo->col_custom_field[i]);
        cinfo->col_custom_field[i] = NULL;
        cinfo->col_custom_dfilter[i] = NULL;
      }
    } else {
      cinfo->col_custom_field[i] = NULL;
      cinfo->col_custom_dfilter[i] = NULL;
    }

    cinfo->fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) * NUM_COL_FMTS);
    get_column_format_matches(cinfo->fmt_matx[i], cinfo->col_fmt[i]);
    cinfo->col_data[i] = NULL;

    if (cinfo->col_fmt[i] == COL_INFO)
      cinfo->col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
    else
      cinfo->col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);

    if(reset_fences)
      cinfo->col_fence[i] = 0;

    cinfo->col_expr.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
    cinfo->col_expr.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
  }

  cinfo->col_expr.col_expr[i] = NULL;
  cinfo->col_expr.col_expr_val[i] = NULL;

  for (i = 0; i < cinfo->num_cols; i++) {
    int j;

    for (j = 0; j < NUM_COL_FMTS; j++) {
      if (!cinfo->fmt_matx[i][j])
          continue;

      if (cinfo->col_first[j] == -1)
        cinfo->col_first[j] = i;

      cinfo->col_last[j] = i;
    }
  }
}
/* Set the filter off a temporary colorfilters and enable it */
void
color_filters_set_tmp(guint8 filt_nr, const gchar *filter, gboolean disabled)
{
    gchar          *name = NULL;
    const gchar    *tmpfilter = NULL;
    GSList         *cfl;
    color_filter_t *colorf;
    dfilter_t      *compiled_filter;
    gchar          *err_msg;
    guint8         i;

    /* Go through the temporary filters and look for the same filter string.
     * If found, clear it so that a filter can be "moved" up and down the list
     */
    for ( i=1 ; i<=10 ; i++ ) {
        /* If we need to reset the temporary filter (filter==NULL), don't look
         * for other rules with the same filter string
         */
        if( i!=filt_nr && filter==NULL )
            continue;

        name = g_strdup_printf("%s%02d",CONVERSATION_COLOR_PREFIX,i);
        cfl = g_slist_find_custom(color_filter_list, name, color_filters_find_by_name_cb);
        colorf = (color_filter_t *)cfl->data;

        /* Only change the filter rule if this is the rule to change or if
         * a matching filter string has been found
         */
        if(colorf && ( (i==filt_nr) || (strstr(filter,colorf->filter_text)!=NULL) ) ) {
            /* set filter string to "frame" if we are resetting the rules
             * or if we found a matching filter string which need to be cleared
             */
            tmpfilter = ( (filter==NULL) || (i!=filt_nr) ) ? "frame" : filter;
            if (!dfilter_compile(tmpfilter, &compiled_filter, &err_msg)) {
                simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
                              "Could not compile color filter name: \"%s\""
                              " text: \"%s\".\n%s", name, filter, err_msg);
                g_free(err_msg);
            } else {
                if (colorf->filter_text != NULL)
                    g_free(colorf->filter_text);
                if (colorf->c_colorfilter != NULL)
                    dfilter_free(colorf->c_colorfilter);
                colorf->filter_text = g_strdup(tmpfilter);
                colorf->c_colorfilter = compiled_filter;
                colorf->disabled = ((i!=filt_nr) ? TRUE : disabled);
                /* Remember that there are now temporary coloring filters set */
                if( filter )
                    tmp_colors_set = TRUE;
            }
        }
        g_free(name);
    }
    return;
}
Example #4
0
void macros_post_update(void) {
	dfilter_t *dfp;
	/* invalidate filter if it stops being valid */
	if (!dfilter_compile(cfile.dfilter, &dfp, NULL)) {
		g_free(cfile.dfilter);
		cfile.dfilter = NULL;
	} else if (dfp) {
		g_free(dfp);
	}
	g_signal_emit_by_name(main_display_filter_widget, "changed");
}
Example #5
0
/* Capture child told us that an error has occurred while parsing a
   capture filter when starting/running the capture.
 */
void
capture_input_cfilter_error_message(capture_session *cap_session, guint i,
                                    char *error_message)
{
  capture_options *capture_opts = cap_session->capture_opts;
  dfilter_t *rfcode = NULL;
  gchar *safe_cfilter;
  gchar *safe_descr;
  gchar *safe_cfilter_error_msg;
  interface_options interface_opts;

  g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture filter error message from child: \"%s\"", error_message);

  g_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
  g_assert(i < capture_opts->ifaces->len);

  interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
  safe_cfilter = simple_dialog_format_message(interface_opts.cfilter);
  safe_descr = simple_dialog_format_message(interface_opts.descr);
  safe_cfilter_error_msg = simple_dialog_format_message(error_message);
  /* Did the user try a display filter? */
  if (dfilter_compile(interface_opts.cfilter, &rfcode) && rfcode != NULL) {
    simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
      "%sInvalid capture filter \"%s\" for interface %s!%s\n"
      "\n"
      "That string looks like a valid display filter; however, it isn't a valid\n"
      "capture filter (%s).\n"
      "\n"
      "Note that display filters and capture filters don't have the same syntax,\n"
      "so you can't use most display filter expressions as capture filters.\n"
      "\n"
      "See the User's Guide for a description of the capture filter syntax.",
      simple_dialog_primary_start(), safe_cfilter, safe_descr,
      simple_dialog_primary_end(), safe_cfilter_error_msg);
      dfilter_free(rfcode);
  } else {
    simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
      "%sInvalid capture filter \"%s\" for interface %s!%s\n"
      "\n"
      "That string isn't a valid capture filter (%s).\n"
      "See the User's Guide for a description of the capture filter syntax.",
      simple_dialog_primary_start(), safe_cfilter, safe_descr,
      simple_dialog_primary_end(), safe_cfilter_error_msg);
  }
  g_free(safe_cfilter_error_msg);
  g_free(safe_descr);
  g_free(safe_cfilter);

  /* the capture child will close the sync_pipe if required, nothing to do for now */
}
Example #6
0
/* this function recompiles dfilter for all registered tap listeners
 */
void
tap_listeners_dfilter_recompile(void)
{
	volatile tap_listener_t *tl;
	dfilter_t *code;
	gchar *err_msg;

	for(tl=tap_listener_queue;tl;tl=tl->next){
		if(tl->code){
			dfilter_free(tl->code);
			tl->code=NULL;
		}
		tl->needs_redraw=TRUE;
		code=NULL;
		if(tl->fstring){
			if(!dfilter_compile(tl->fstring, &code, &err_msg)){
				g_free(err_msg);
				/* Not valid, make a dfilter matching no packets */
				dfilter_compile("frame.number == 0", &code, &err_msg);
			}
		}
		tl->code=code;
	}
}
Example #7
0
static void
color_filter_compile_cb(gpointer filter_arg, gpointer unused _U_)
{
	color_filter_t *colorf = (color_filter_t *)filter_arg;

	g_assert(colorf->c_colorfilter == NULL);
	if (!dfilter_compile(colorf->filter_text, &colorf->c_colorfilter)) {
		simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
		"Could not compile color filter name: \"%s\" text: \"%s\".\n%s",
			      colorf->filter_name, colorf->filter_text, dfilter_error_msg);
		/* this filter was compilable before, so this should never happen */
		/* except if the OK button of the parent window has been clicked */
		/* so don't use g_assert_not_reached() but check the filters again */
	}
}
Example #8
0
static void
color_filter_validate_cb(gpointer filter_arg, gpointer unused _U_)
{
	color_filter_t *colorf = (color_filter_t *)filter_arg;

	g_assert(colorf->c_colorfilter == NULL);
	if (!dfilter_compile(colorf->filter_text, &colorf->c_colorfilter)) {
		simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
		"Removing color filter name: \"%s\" text: \"%s\".\n%s",
			      colorf->filter_name, colorf->filter_text, dfilter_error_msg);
		/* Delete the color filter from the list of color filters. */
		color_filter_valid_list = g_slist_remove(color_filter_valid_list, colorf);
		color_filter_delete(colorf);
	}
}
Example #9
0
/* this function sets a new dfilter to a tap listener
 */
GString *
set_tap_dfilter(void *tapdata, const char *fstring)
{
	volatile tap_listener_t *tl=NULL,*tl2;
	dfilter_t *code=NULL;
	GString *error_string;
	gchar *err_msg;

	if(!tap_listener_queue){
		return NULL;
	}

	if(tap_listener_queue->tapdata==tapdata){
		tl=tap_listener_queue;
	} else {
		for(tl2=tap_listener_queue;tl2->next;tl2=tl2->next){
			if(tl2->next->tapdata==tapdata){
				tl=tl2->next;
				break;
			}

		}
	}

	if(tl){
		if(tl->code){
			dfilter_free(tl->code);
			tl->code=NULL;
		}
		tl->needs_redraw=TRUE;
		g_free(tl->fstring);
		if(fstring){
			if(!dfilter_compile(fstring, &code, &err_msg)){
				tl->fstring=NULL;
				error_string = g_string_new("");
				g_string_printf(error_string,
						 "Filter \"%s\" is invalid - %s",
						 fstring, err_msg);
				g_free(err_msg);
				return error_string;
			}
		}
		tl->fstring=g_strdup(fstring);
		tl->code=code;
	}

	return NULL;
}
void ColumnPreferencesFrame::customFieldTextChanged(QString)
{
    SyntaxLineEdit *syntax_edit = qobject_cast<SyntaxLineEdit *>(cur_line_edit_);
    QTreeWidgetItem *item = ui->columnTreeWidget->currentItem();
    if (!syntax_edit || !item) return;

    dfilter_t *dfp = NULL;
    const char *field_text = syntax_edit->text().toUtf8().constData();
    if (strlen(field_text) < 1) {
        syntax_edit->setSyntaxState(SyntaxLineEdit::Empty);
    } else if (!dfilter_compile(field_text, &dfp)) {
        syntax_edit->setSyntaxState(SyntaxLineEdit::Invalid);
    } else {
        syntax_edit->setSyntaxState(SyntaxLineEdit::Valid);
    }
    dfilter_free(dfp);
}
Example #11
0
static void
color_filter_validate_cb(gpointer filter_arg, gpointer err)
{
    color_filter_t *colorf = (color_filter_t *)filter_arg;
    gchar **err_msg = (gchar**)err;
    gchar *local_err_msg;

    g_assert(colorf->c_colorfilter == NULL);
    if (!dfilter_compile(colorf->filter_text, &colorf->c_colorfilter, &local_err_msg)) {
        *err_msg = g_strdup_printf("Removing color filter name: \"%s\" text: \"%s\".\n%s",
                      colorf->filter_name, colorf->filter_text, local_err_msg);
        g_free(local_err_msg);
        /* Delete the color filter from the list of color filters. */
        color_filter_valid_list = g_slist_remove(color_filter_valid_list, colorf);
        color_filter_delete(colorf);
    }
}
Example #12
0
static void
color_filter_compile_cb(gpointer filter_arg, gpointer err)
{
    color_filter_t *colorf = (color_filter_t *)filter_arg;
    gchar **err_msg = (gchar**)err;
    gchar *local_err_msg = NULL;

    g_assert(colorf->c_colorfilter == NULL);
    if (!dfilter_compile(colorf->filter_text, &colorf->c_colorfilter, &local_err_msg)) {
        *err_msg = g_strdup_printf("Could not compile color filter name: \"%s\" text: \"%s\".\n%s",
                      colorf->filter_name, colorf->filter_text, local_err_msg);
        g_free(local_err_msg);
        /* this filter was compilable before, so this should never happen */
        /* except if the OK button of the parent window has been clicked */
        /* so don't use g_assert_not_reached() but check the filters again */
    }
}
void DisplayFilterEdit::checkFilter(const QString& text)
{
    dfilter_t *dfp;
    guchar c;

    clear_button_->setVisible(!text.isEmpty());

    popFilterSyntaxStatus();

    if (field_name_only_ && (c = proto_check_field_name(text.toUtf8().constData()))) {
        setSyntaxState(Invalid);
        emit pushFilterSyntaxStatus(QString().sprintf("Illegal character in field name: '%c'", c));
    } else if (dfilter_compile(text.toUtf8().constData(), &dfp)) {
        GPtrArray *depr = NULL;
        if (dfp != NULL) {
            depr = dfilter_deprecated_tokens(dfp);
        }
        if (text.isEmpty()) {
            setSyntaxState(Empty);
        } else if (depr) {
            /* You keep using that word. I do not think it means what you think it means. */
            setSyntaxState(Deprecated);
            /*
             * We're being lazy and only printing the first "problem" token.
             * Would it be better to print all of them?
             */
            emit pushFilterSyntaxWarning(QString().sprintf("\"%s\" may have unexpected results (see the User's Guide)",
                                                          (const char *) g_ptr_array_index(depr, 0)));
        } else {
            setSyntaxState(Valid);
        }
        dfilter_free(dfp);
    } else {
        setSyntaxState(Invalid);
        QString invalidMsg(tr("Invalid filter"));
        if (dfilter_error_msg) {
            invalidMsg.append(QString().sprintf(": %s", dfilter_error_msg));
        }
        emit pushFilterSyntaxStatus(invalidMsg);
    }

    bookmark_button_->setEnabled(syntaxState() == Valid || syntaxState() == Deprecated);
    if (apply_button_) {
        apply_button_->setEnabled(SyntaxState() != Invalid);
    }
}
Example #14
0
/* this function attaches the tap_listener to the named tap.
 * function returns :
 *     NULL: ok.
 * non-NULL: error, return value points to GString containing error
 *           message.
 */
GString *
register_tap_listener(const char *tapname, void *tapdata, const char *fstring,
		      guint flags, tap_reset_cb reset, tap_packet_cb packet, tap_draw_cb draw)
{
	volatile tap_listener_t *tl;
	int tap_id;
	dfilter_t *code=NULL;
	GString *error_string;
	gchar *err_msg;

	tap_id=find_tap_id(tapname);
	if(!tap_id){
		error_string = g_string_new("");
		g_string_printf(error_string, "Tap %s not found", tapname);
		return error_string;
	}

	tl=(volatile tap_listener_t *)g_malloc0(sizeof(tap_listener_t));
	tl->needs_redraw=TRUE;
	tl->flags=flags;
	if(fstring){
		if(!dfilter_compile(fstring, &code, &err_msg)){
			error_string = g_string_new("");
			g_string_printf(error_string,
			    "Filter \"%s\" is invalid - %s",
			    fstring, err_msg);
			g_free(err_msg);
			free_tap_listener(tl);
			return error_string;
		}
	}
	tl->fstring=g_strdup(fstring);
	tl->code=code;

	tl->tap_id=tap_id;
	tl->tapdata=tapdata;
	tl->reset=reset;
	tl->packet=packet;
	tl->draw=draw;
	tl->next=tap_listener_queue;

	tap_listener_queue=tl;

	return NULL;
}
void ColoringRulesDialog::updateWidgets()
{
    QString hint = "<small><i>";
    int num_selected = ui->coloringRulesTreeWidget->selectedItems().count();

    if (num_selected == 1) {
        QTreeWidgetItem *ti = ui->coloringRulesTreeWidget->currentItem();
        QString color_button_ss =
                "QPushButton {"
                "  border: 1px solid palette(Dark);"
                "  padding-left: %1px;"
                "  padding-right: %1px;"
                "  color: %2;"
                "  background-color: %3;"
                "}";
        int one_em = fontMetrics().height();
        QString fg_color = ti->foreground(0).color().name();
        QString bg_color = ti->background(0).color().name();
        ui->fGPushButton->setStyleSheet(color_button_ss.arg(one_em).arg(bg_color).arg(fg_color));
        ui->bGPushButton->setStyleSheet(color_button_ss.arg(one_em).arg(fg_color).arg(bg_color));
    }

    ui->copyToolButton->setEnabled(num_selected == 1);
    ui->deleteToolButton->setEnabled(num_selected > 0);
    ui->fGPushButton->setVisible(num_selected == 1);
    ui->bGPushButton->setVisible(num_selected == 1);

    QString error_text;
    QTreeWidgetItemIterator iter(ui->coloringRulesTreeWidget);
    bool enable_save = true;

    while (*iter) {
        QTreeWidgetItem *item = (*iter);
        if (item->text(name_col_).contains("@")) {
            error_text = tr("the \"@\" symbol will be ignored.");
        }

        // Check the rule's display filter syntax only if it's checked.
        QString display_filter = item->text(filter_col_);
        if (!display_filter.isEmpty() && item->checkState(name_col_) == Qt::Checked) {
            dfilter_t *dfilter;
            bool status;
            gchar *err_msg;
            status = dfilter_compile(display_filter.toUtf8().constData(), &dfilter, &err_msg);
            dfilter_free(dfilter);
            if (!status) {
                if (!error_text.isEmpty()) error_text += " ";
                error_text += err_msg;
                g_free(err_msg);
                enable_save = false;
            }
        }

        if (!error_text.isEmpty()) {
            error_text.prepend(QString("%1: ").arg(item->text(name_col_)));
            break;
        }
        ++iter;
    }

    if (error_text.isEmpty()) {
        hint += tr("Double click to edit. Drag to move. Rules are processed in order until a match is found.");
    } else {
        hint += error_text;
    }
    hint += "</i></small>";
    ui->hintLabel->setText(hint);

    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(enable_save);
}
Example #16
0
int
main(int argc, char **argv)
{
	char		*init_progfile_dir_error;
	char		*text;
	char		*gpf_path, *pf_path;
	int		gpf_open_errno, gpf_read_errno;
	int		pf_open_errno, pf_read_errno;
	dfilter_t	*df;

	/*
	 * Get credential information for later use.
	 */
	init_process_policies();

	/*
	 * Attempt to get the pathname of the executable file.
	 */
	init_progfile_dir_error = init_progfile_dir(argv[0], main);
	if (init_progfile_dir_error != NULL) {
		fprintf(stderr, "dftest: Can't get pathname of dftest program: %s.\n",
			init_progfile_dir_error);
	}

	timestamp_set_type(TS_RELATIVE);
	timestamp_set_seconds_type(TS_SECONDS_DEFAULT);

	/* Register all dissectors; we must do this before checking for the
	   "-g" flag, as the "-g" flag dumps a list of fields registered
	   by the dissectors, and we must do it before we read the preferences,
	   in case any dissectors register preferences. */
	epan_init(register_all_protocols,
		  register_all_protocol_handoffs, NULL, NULL,
		  failure_message, open_failure_message, read_failure_message,
		  write_failure_message);

	/* now register the preferences for any non-dissector modules.
	we must do that before we read the preferences as well. */
	prefs_register_modules();

	/* set the c-language locale to the native environment. */
	setlocale(LC_ALL, "");

	read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
		&pf_open_errno, &pf_read_errno, &pf_path);
	if (gpf_path != NULL) {
		if (gpf_open_errno != 0) {
			fprintf(stderr,
				"can't open global preferences file \"%s\": %s.\n",
				pf_path, g_strerror(gpf_open_errno));
		}
		if (gpf_read_errno != 0) {
			fprintf(stderr,
				"I/O error reading global preferences file \"%s\": %s.\n",
				pf_path, g_strerror(gpf_read_errno));
		}
	}
	if (pf_path != NULL) {
		if (pf_open_errno != 0) {
			fprintf(stderr,
				"can't open your preferences file \"%s\": %s.\n",
				pf_path, g_strerror(pf_open_errno));
		}
		if (pf_read_errno != 0) {
			fprintf(stderr,
				"I/O error reading your preferences file \"%s\": %s.\n",
				pf_path, g_strerror(pf_read_errno));
		}
	}

	/* notify all registered modules that have had any of their preferences
	changed either from one of the preferences file or from the command
	line that its preferences have changed. */
	prefs_apply_all();

	/* Check for filter on command line */
	if (argc <= 1) {
		fprintf(stderr, "Usage: dftest <filter>\n");
		exit(1);
	}

	/* Get filter text */
	text = get_args_as_string(argc, argv, 1);

	printf("Filter: \"%s\"\n", text);

	/* Compile it */
	if (!dfilter_compile(text, &df)) {
		fprintf(stderr, "dftest: %s\n", dfilter_error_msg);
		epan_cleanup();
		exit(2);
	}
	printf("dfilter ptr = 0x%08x\n", GPOINTER_TO_INT(df));

	printf("\n\n");

	if (df == NULL)
		printf("Filter is empty\n");
	else
		dfilter_dump(df);

	dfilter_free(df);
	epan_cleanup();
	exit(0);
}
Example #17
0
/**
 * This function processes a specified capture file with the specified fields of interest
 * and display filter.  This function calls the appropriate language-specific callback
 * function in <cb> to manipulate data structures in the caller's scope.
 * 
 * @param filename valid pcap file
 * @param nfields a positive integer describing the number of fields
 * @param fields an array of strings
 * @return 0 on success, else error.
 */
glong sharktools_get_cb(gchar *filename, gulong nfields, const gchar **fields,
                       gchar *dfilterorig, sharktools_callbacks *cb)
{
  gsize i;
  capture_file cfile;
  gchar *cf_name = NULL;
  char *dfilter;
  dfilter_t *rfcode = NULL;

  // Create an stdata struct on the stack
  st_data_t stdata;

  dprintf("%s: entering...\n", __FUNCTION__);

  dprintf("%s: dfilterorig: %s\n", __FUNCTION__, dfilterorig);

  dfilter = strdup(dfilterorig);

  dprintf("%s: dfilter: %s\n", __FUNCTION__, dfilter);

  if(!dfilter_compile(dfilter, &rfcode))
    {
      sprintf(errmsg, "%s", dfilter_error_msg);
      printf("errmsg");
      if(rfcode)
        dfilter_free(rfcode);
      return -1;
    }

  // Defined in cfile.c, looks easy enough to use
  cap_file_init(&cfile);

  cf_name = filename;

  // Open pcap file
  int err;
  if(cf_open(&cfile, cf_name, FALSE, &err) != CF_OK)
    {
      //sprintf(errmsg, "%s", dfilter_error_msg);
      if(rfcode)
        dfilter_free(rfcode);
      return -1;
    }

  dprintf("nfields = %ld\n", nfields);

  stdata_init(&stdata, nfields);

  stdata_add_fields(&stdata, fields, nfields);

  dprintf("stdata.fields->len = %d\n", stdata.fields->len);

  dprintf("stdata.field_values_str = %lX\n", (glong)stdata.field_values_str);
  dprintf("stdata.field_types = %lX\n", (glong)stdata.field_types);
  
  dprintf("%s: opened file\n", __FUNCTION__);

  cfile.rfcode = rfcode;

  gchar        *err_info;
  gint64       data_offset;

  // Read and process each packet one at a time
  while(wtap_read(cfile.wth, &err, &err_info, &data_offset))
    {
      dprintf("*******************************\n");

      // (Re)-set all the stdata.field_{values,types} fields
      for(i = 0; i < nfields; i++)
        {
          stdata.field_values_str[i] = 0;
          stdata.field_types[i] = FT_NONE;
        }

      gboolean passed = FALSE;
      
      passed = process_packet(&cfile, data_offset, &stdata);

      if(passed)
	{
          gpointer row = cb->row_new(cb);

	  for(i = 0; i < nfields; i++)
	    {
              gpointer key;
              key = cb->keys[i];

              dprintf("key = %p\n", key);

	      dprintf("values[%ld] = %p\n", i, stdata.field_values_str[i]);
	      dprintf("types[%ld] = %ld\n", i, stdata.field_types[i]);

              cb->row_set(cb, row, key,
                          stdata.field_types[i],
                          stdata.field_values_native[i],
                          stdata.field_values_str[i]
                          );
            }

          cb->row_add(cb, row);
        }
    }

  if(rfcode)
    dfilter_free(rfcode);
  wtap_close(cfile.wth);
  cfile.wth = NULL;

  stdata_cleanup(&stdata);

  dprintf("%s: ...leaving.\n", __FUNCTION__);

  return 0;
}
Example #18
0
/**
 * This function returns the number of packets in <filename> that would
 * pass through the filter <dfilter>.  This was necessary to mitigate memory
 * usage in Matlab, where dynamically-growing or shrinking data structures
 * (apparently) don't exist.  If it looks hacky, it is :-)
 *
 * NB: there is a race condition between running sharktools_count() and
 * sharktools_get_cb(), since we close and reopen the pcap file in between.
 */
glong sharktools_count(char *filename, char *dfilter)
{
  capture_file cfile;
  gchar *cf_name = NULL;
  dfilter_t *rfcode = NULL;
  glong count = 0;

  dprintf("%s: entering...\n", __FUNCTION__);

  dprintf("%s: dfilter: %s\n", __FUNCTION__, dfilter);
  if(!dfilter_compile(dfilter, &rfcode))
    {
      sprintf(errmsg, "%s", dfilter_error_msg);
      printf("errmsg");
      if(rfcode)
        dfilter_free(rfcode);
      return -1;
    }

  // Defined in cfile.c, looks easy enough to use
  cap_file_init(&cfile);

  cf_name = filename;

  // Open pcap file
  int err;
  if(cf_open(&cfile, cf_name, FALSE, &err) != CF_OK)
    {
      //sprintf(errmsg, "%s", dfilter_error_msg);
      if(rfcode)
        dfilter_free(rfcode);
      return -1;
    }

  dprintf("%s: opened file\n", __FUNCTION__);

  cfile.rfcode = rfcode;

  gchar        *err_info;
  gint64       data_offset;

  // Read and process each packet one at a time
  while(wtap_read(cfile.wth, &err, &err_info, &data_offset))
    {
      gboolean passed = TRUE;
      
      // Only process packets if there's a display filter specified
      if(dfilter != NULL && *dfilter != '\0')
        {
          // Passing in NULL for st_data_t means we're just counting
          passed = process_packet(&cfile, data_offset, NULL);
        }

      if(passed)
	{
          count++;
          //dprintf("count! %d\n", count);
        }
    }

  if(rfcode)
    dfilter_free(rfcode);
  wtap_close(cfile.wth);
  cfile.wth = NULL;

  return count;
}
Example #19
0
/* XXX - Would it make more sense to use GStrings here instead of reallocing
   our buffers? */
static gboolean
read_filters_file(FILE *f, gpointer user_data)
{
#define INIT_BUF_SIZE 128
    gchar    *name             = NULL;
    gchar    *filter_exp       = NULL;
    guint32   name_len         = INIT_BUF_SIZE;
    guint32   filter_exp_len   = INIT_BUF_SIZE;
    guint32   i                = 0;
    int       c;
    guint16   fg_r, fg_g, fg_b, bg_r, bg_g, bg_b;
    gboolean  disabled         = FALSE;
    gboolean  skip_end_of_line = FALSE;

    name = (gchar *)g_malloc(name_len + 1);
    filter_exp = (gchar *)g_malloc(filter_exp_len + 1);

    while (1) {

        if (skip_end_of_line) {
            do {
                c = getc(f);
            } while (c != EOF && c != '\n');
            if (c == EOF)
                break;
            disabled = FALSE;
            skip_end_of_line = FALSE;
        }

        while ((c = getc(f)) != EOF && g_ascii_isspace(c)) {
            if (c == '\n') {
                continue;
            }
        }

        if (c == EOF)
            break;

        if (c == '!') {
            disabled = TRUE;
            continue;
        }

        /* skip # comments and invalid lines */
        if (c != '@') {
            skip_end_of_line = TRUE;
            continue;
        }

        /* we get the @ delimiter.
         * Format is:
         * @name@filter expression@[background r,g,b][foreground r,g,b]
         */

        /* retrieve name */
        i = 0;
        while (1) {
            c = getc(f);
            if (c == EOF || c == '@')
                break;
            if (i >= name_len) {
                /* buffer isn't long enough; double its length.*/
                name_len *= 2;
                name = (gchar *)g_realloc(name, name_len + 1);
            }
            name[i++] = c;
        }
        name[i] = '\0';

        if (c == EOF) {
            break;
        } else if (i == 0) {
            skip_end_of_line = TRUE;
            continue;
        }

        /* retrieve filter expression */
        i = 0;
        while (1) {
            c = getc(f);
            if (c == EOF || c == '@')
                break;
            if (i >= filter_exp_len) {
                /* buffer isn't long enough; double its length.*/
                filter_exp_len *= 2;
                filter_exp = (gchar *)g_realloc(filter_exp, filter_exp_len + 1);
            }
            filter_exp[i++] = c;
        }
        filter_exp[i] = '\0';

        if (c == EOF) {
            break;
        } else if (i == 0) {
            skip_end_of_line = TRUE;
            continue;
        }

        /* retrieve background and foreground colors */
        if (fscanf(f,"[%hu,%hu,%hu][%hu,%hu,%hu]",
                   &bg_r, &bg_g, &bg_b, &fg_r, &fg_g, &fg_b) == 6) {

            /* we got a complete color filter */

            color_t bg_color, fg_color;
            color_filter_t *colorf;
            dfilter_t *temp_dfilter;
            gchar *err_msg;

            if (!dfilter_compile(filter_exp, &temp_dfilter, &err_msg)) {
                g_warning("Could not compile \"%s\" in colorfilters file.\n%s",
                          name, err_msg);
                g_free(err_msg);
                prefs.unknown_colorfilters = TRUE;

                skip_end_of_line = TRUE;
                continue;
            }

            if (!initialize_color(&fg_color, fg_r, fg_g, fg_b)) {
                /* oops */
                simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
                              "Could not allocate foreground color "
                              "specified in input file for %s.", name);
                dfilter_free(temp_dfilter);
                skip_end_of_line = TRUE;
                continue;
            }
            if (!initialize_color(&bg_color, bg_r, bg_g, bg_b)) {
                /* oops */
                simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
                              "Could not allocate background color "
                              "specified in input file for %s.", name);
                dfilter_free(temp_dfilter);
                skip_end_of_line = TRUE;
                continue;
            }

            colorf = color_filter_new(name, filter_exp, &bg_color,
                                      &fg_color, disabled);
            if(user_data == &color_filter_list) {
                GSList **cfl = (GSList **)user_data;

                /* internal call */
                colorf->c_colorfilter = temp_dfilter;
                *cfl = g_slist_append(*cfl, colorf);
            } else {
                /* external call */
                /* just editing, don't need the compiled filter */
                dfilter_free(temp_dfilter);
                color_filter_add_cb (colorf, user_data);
            }
        }    /* if sscanf */

        skip_end_of_line = TRUE;
    }

    g_free(name);
    g_free(filter_exp);
    return TRUE;
}
Example #20
0
int
main(int argc, char *argv[])
{
  char                *init_progfile_dir_error;
  int                  opt, i;
  extern char         *optarg;
  gboolean             arg_error = FALSE;

#ifdef _WIN32
  WSADATA		wsaData;
#endif	/* _WIN32 */

  char                *gpf_path, *pf_path;
  char                *gdp_path, *dp_path;
  int                  gpf_open_errno, gpf_read_errno;
  int                  pf_open_errno, pf_read_errno;
  int                  gdp_open_errno, gdp_read_errno;
  int                  dp_open_errno, dp_read_errno;
  int                  err;
  gchar               *pipe_name = NULL;
  gchar               *rfilters[64];
  e_prefs             *prefs;
  char                 badopt;
  GLogLevelFlags       log_flags;
  GPtrArray           *disp_fields = g_ptr_array_new();
  guint                fc;
  gboolean             skip_pcap_header = FALSE;

  #define OPTSTRING_INIT "d:F:hlnN:o:r:R:sS:t:v"

  static const char    optstring[] = OPTSTRING_INIT;

  /*
   * Get credential information for later use.
   */
  get_credential_info();

  /*
   * Clear the filters arrays
   */
  memset(rfilters, 0, sizeof(rfilters));
  memset(rfcodes, 0, sizeof(rfcodes));
  n_rfilters = 0;
  n_rfcodes = 0;

  /*
   * Initialize our string format
   */
  string_fmts = g_ptr_array_new();

  /*
   * Attempt to get the pathname of the executable file.
   */
  init_progfile_dir_error = init_progfile_dir(argv[0], main);
  if (init_progfile_dir_error != NULL) {
    fprintf(stderr, "rawshark: Can't get pathname of rawshark program: %s.\n",
            init_progfile_dir_error);
  }

  /*
   * Get credential information for later use.
   */
  get_credential_info();

  /* nothing more than the standard GLib handler, but without a warning */
  log_flags =
		    G_LOG_LEVEL_WARNING |
		    G_LOG_LEVEL_MESSAGE |
		    G_LOG_LEVEL_INFO |
		    G_LOG_LEVEL_DEBUG;

  g_log_set_handler(NULL,
		    log_flags,
		    log_func_ignore, NULL /* user_data */);
  g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
		    log_flags,
		    log_func_ignore, NULL /* user_data */);

  timestamp_set_type(TS_RELATIVE);
  timestamp_set_precision(TS_PREC_AUTO);

  /* Register all dissectors; we must do this before checking for the
     "-G" flag, as the "-G" flag dumps information registered by the
     dissectors, and we must do it before we read the preferences, in
     case any dissectors register preferences. */
  epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
            failure_message, open_failure_message, read_failure_message,
            write_failure_message);

  /* Now register the preferences for any non-dissector modules.
     We must do that before we read the preferences as well. */
  prefs_register_modules();

  /* Set the C-language locale to the native environment. */
  setlocale(LC_ALL, "");

  prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
                     &pf_open_errno, &pf_read_errno, &pf_path);
  if (gpf_path != NULL) {
    if (gpf_open_errno != 0) {
      cmdarg_err("Can't open global preferences file \"%s\": %s.",
              pf_path, strerror(gpf_open_errno));
    }
    if (gpf_read_errno != 0) {
      cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
              pf_path, strerror(gpf_read_errno));
    }
  }
  if (pf_path != NULL) {
    if (pf_open_errno != 0) {
      cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
              strerror(pf_open_errno));
    }
    if (pf_read_errno != 0) {
      cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
              pf_path, strerror(pf_read_errno));
    }
    g_free(pf_path);
    pf_path = NULL;
  }

  /* Set the name resolution code's flags from the preferences. */
  g_resolv_flags = prefs->name_resolve;

  /* Read the disabled protocols file. */
  read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
                            &dp_path, &dp_open_errno, &dp_read_errno);
  if (gdp_path != NULL) {
    if (gdp_open_errno != 0) {
      cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
                 gdp_path, strerror(gdp_open_errno));
    }
    if (gdp_read_errno != 0) {
      cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
                 gdp_path, strerror(gdp_read_errno));
    }
    g_free(gdp_path);
  }
  if (dp_path != NULL) {
    if (dp_open_errno != 0) {
      cmdarg_err(
        "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
        strerror(dp_open_errno));
    }
    if (dp_read_errno != 0) {
      cmdarg_err(
        "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
        strerror(dp_read_errno));
    }
    g_free(dp_path);
  }

#ifdef _WIN32
  /* Load Wpcap, if possible */
  load_wpcap();
#endif

  init_cap_file(&cfile);

  /* Assemble the compile-time version information string */
  comp_info_str = g_string_new("Compiled ");
  get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);

  /* Assemble the run-time version information string */
  runtime_info_str = g_string_new("Running ");
  get_runtime_version_info(runtime_info_str, NULL);

  /* Print format defaults to this. */
  print_format = PR_FMT_TEXT;

  /* Initialize our encapsulation type */
  encap = WTAP_ENCAP_UNKNOWN;

  /* Now get our args */
  /* XXX - We should probably have an option to dump libpcap link types */
  while ((opt = getopt(argc, argv, optstring)) != -1) {
    switch (opt) {
      case 'd':        /* Payload type */
        if (!set_link_type(optarg)) {
          cmdarg_err("Invalid link type or protocol \"%s\"", optarg);
          exit(1);
        }
        break;
      case 'F':        /* Read field to display */
        g_ptr_array_add(disp_fields, g_strdup(optarg));
        break;
      case 'h':        /* Print help and exit */
        print_usage(TRUE);
        exit(0);
        break;
      case 'l':        /* "Line-buffer" standard output */
        /* This isn't line-buffering, strictly speaking, it's just
           flushing the standard output after the information for
           each packet is printed; however, that should be good
           enough for all the purposes to which "-l" is put (and
           is probably actually better for "-V", as it does fewer
           writes).

           See the comment in "process_packet()" for an explanation of
           why we do that, and why we don't just use "setvbuf()" to
           make the standard output line-buffered (short version: in
           Windows, "line-buffered" is the same as "fully-buffered",
           and the output buffer is only flushed when it fills up). */
        line_buffered = TRUE;
        break;
      case 'n':        /* No name resolution */
        g_resolv_flags = RESOLV_NONE;
        break;
      case 'N':        /* Select what types of addresses/port #s to resolve */
        if (g_resolv_flags == RESOLV_ALL)
          g_resolv_flags = RESOLV_NONE;
        badopt = string_to_name_resolve(optarg, &g_resolv_flags);
        if (badopt != '\0') {
          cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
                     badopt);
          exit(1);
        }
        break;
      case 'o':        /* Override preference from command line */
        switch (prefs_set_pref(optarg)) {

        case PREFS_SET_OK:
          break;

        case PREFS_SET_SYNTAX_ERR:
          cmdarg_err("Invalid -o flag \"%s\"", optarg);
          exit(1);
          break;

        case PREFS_SET_NO_SUCH_PREF:
        case PREFS_SET_OBSOLETE:
          cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
          exit(1);
          break;
        }
        break;
      case 'r':        /* Read capture file xxx */
        pipe_name = g_strdup(optarg);
        break;
      case 'R':        /* Read file filter */
        if(n_rfilters < (int) sizeof(rfilters) / (int) sizeof(rfilters[0])) {
          rfilters[n_rfilters++] = optarg;
        }
        else {
          cmdarg_err("Too many display filters");
          exit(1);
        }
        break;
      case 's':        /* Skip PCAP header */
        skip_pcap_header = TRUE;
        break;
      case 'S':        /* Print string representations */
        if (!parse_field_string_format(optarg)) {
          cmdarg_err("Invalid field string format");
          exit(1);
        }
        break;
      case 't':        /* Time stamp type */
        if (strcmp(optarg, "r") == 0)
          timestamp_set_type(TS_RELATIVE);
        else if (strcmp(optarg, "a") == 0)
          timestamp_set_type(TS_ABSOLUTE);
        else if (strcmp(optarg, "ad") == 0)
          timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
        else if (strcmp(optarg, "d") == 0)
          timestamp_set_type(TS_DELTA);
        else if (strcmp(optarg, "dd") == 0)
          timestamp_set_type(TS_DELTA_DIS);
        else if (strcmp(optarg, "e") == 0)
          timestamp_set_type(TS_EPOCH);
        else {
          cmdarg_err("Invalid time stamp type \"%s\"",
            optarg);
          cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
          cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
          exit(1);
        }
        break;
      case 'v':        /* Show version and exit */
        printf("Rawshark " VERSION "%s\n"
               "\n"
               "%s"
               "\n"
               "%s"
               "\n"
               "%s",
               wireshark_svnversion, get_copyright_info(), comp_info_str->str,
               runtime_info_str->str);
        exit(0);
        break;

      default:
      case '?':        /* Bad flag - print usage message */
        print_usage(TRUE);
        exit(1);
        break;
    }
  }

  /* Notify all registered modules that have had any of their preferences
     changed either from one of the preferences file or from the command
     line that their preferences have changed.
     Initialize preferences before display filters, otherwise modules
     like MATE won't work. */
  prefs_apply_all();

  /* Initialize our display fields */
  for (fc = 0; fc < disp_fields->len; fc++) {
	protocolinfo_init(g_ptr_array_index(disp_fields, fc));
  }
  g_ptr_array_free(disp_fields, TRUE);
  printf("\n");
  fflush(stdout);

  /* If no capture filter or read filter has been specified, and there are
     still command-line arguments, treat them as the tokens of a capture
     filter (if no "-r" flag was specified) or a read filter (if a "-r"
     flag was specified. */
  if (optind < argc) {
    if (pipe_name != NULL) {
      if (n_rfilters != 0) {
        cmdarg_err("Read filters were specified both with \"-R\" "
            "and with additional command-line arguments");
        exit(1);
      }
      rfilters[n_rfilters] = get_args_as_string(argc, argv, optind);
    }
  }

  /* Make sure we got a dissector handle for our payload. */
  if (encap == WTAP_ENCAP_UNKNOWN) {
    cmdarg_err("No valid payload dissector specified.");
    exit(1);
  }

  if (arg_error) {
    print_usage(FALSE);
    exit(1);
  }


#ifdef _WIN32
  /* Start windows sockets */
  WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
#endif /* _WIN32 */

  /* At this point MATE will have registered its field array so we can
     have a tap filter with one of MATE's late-registered fields as part
     of the filter.  We can now process all the "-z" arguments. */
  start_requested_stats();

  /* disabled protocols as per configuration file */
  if (gdp_path == NULL && dp_path == NULL) {
    set_disabled_protos_list();
  }

  /* Build the column format array */
  col_setup(&cfile.cinfo, prefs->num_cols);
  for (i = 0; i < cfile.cinfo.num_cols; i++) {
    cfile.cinfo.col_fmt[i] = get_column_format(i);
    cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
    cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
      NUM_COL_FMTS);
    get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
    cfile.cinfo.col_data[i] = NULL;
    if (cfile.cinfo.col_fmt[i] == COL_INFO)
      cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
    else
      cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
    cfile.cinfo.col_fence[i] = 0;
    cfile.cinfo.col_expr.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
    cfile.cinfo.col_expr.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
  }

  for (i = 0; i < cfile.cinfo.num_cols; i++) {
      int j;

      for (j = 0; j < NUM_COL_FMTS; j++) {
         if (!cfile.cinfo.fmt_matx[i][j])
             continue;

         if (cfile.cinfo.col_first[j] == -1)
             cfile.cinfo.col_first[j] = i;
         cfile.cinfo.col_last[j] = i;
      }
  }

  if (n_rfilters != 0) {
    for (i = 0; i < n_rfilters; i++) {
      if (!dfilter_compile(rfilters[i], &rfcodes[n_rfcodes])) {
        cmdarg_err("%s", dfilter_error_msg);
        epan_cleanup();
        exit(2);
      }
      n_rfcodes++;
    }
  }

  if (pipe_name) {
    /*
     * We're reading a pipe (or capture file).
     */

    /*
     * Immediately relinquish any special privileges we have; we must not
     * be allowed to read any capture files the user running Rawshark
     * can't open.
     */
    relinquish_special_privs_perm();

    if (raw_cf_open(&cfile, pipe_name) != CF_OK) {
      epan_cleanup();
      exit(2);
    }

    /* Do we need to PCAP header and magic? */
    if (skip_pcap_header) {
      guint bytes_left = sizeof(struct pcap_hdr) + sizeof(guint32);
      gchar buf[sizeof(struct pcap_hdr) + sizeof(guint32)];
      while (bytes_left > 0) {
          guint bytes = read(fd, buf, bytes_left);
          if (bytes <= 0) {
              cmdarg_err("Not enough bytes for pcap header.");
              exit(2);
          }
          bytes_left -= bytes;
      }
    }

    /* Set timestamp precision; there should arguably be a command-line
       option to let the user set this. */
#if 0
    switch(wtap_file_tsprecision(cfile.wth)) {
    case(WTAP_FILE_TSPREC_SEC):
      timestamp_set_precision(TS_PREC_AUTO_SEC);
      break;
    case(WTAP_FILE_TSPREC_DSEC):
      timestamp_set_precision(TS_PREC_AUTO_DSEC);
      break;
    case(WTAP_FILE_TSPREC_CSEC):
      timestamp_set_precision(TS_PREC_AUTO_CSEC);
      break;
    case(WTAP_FILE_TSPREC_MSEC):
      timestamp_set_precision(TS_PREC_AUTO_MSEC);
      break;
    case(WTAP_FILE_TSPREC_USEC):
      timestamp_set_precision(TS_PREC_AUTO_USEC);
      break;
    case(WTAP_FILE_TSPREC_NSEC):
      timestamp_set_precision(TS_PREC_AUTO_NSEC);
      break;
    default:
      g_assert_not_reached();
    }
#else
    timestamp_set_precision(TS_PREC_AUTO_USEC);
#endif

    /* Process the packets in the file */
    err = load_cap_file(&cfile);

    if (err != 0) {
      epan_cleanup();
      exit(2);
    }
  } else {
    /* If you want to capture live packets, use TShark. */
    cmdarg_err("Input file or pipe name not specified.");
    exit(2);
  }

  epan_cleanup();

  return 0;
}
Example #21
0
/* XXX - Would it make more sense to use GStrings here instead of reallocing
   our buffers? */
static int
read_filters_file(const gchar *path, FILE *f, gpointer user_data, color_filter_add_cb_func add_cb)
{
#define INIT_BUF_SIZE 128
    gchar    *name             = NULL;
    gchar    *filter_exp       = NULL;
    guint32   name_len         = INIT_BUF_SIZE;
    guint32   filter_exp_len   = INIT_BUF_SIZE;
    guint32   i                = 0;
    int       c;
    guint16   fg_r, fg_g, fg_b, bg_r, bg_g, bg_b;
    gboolean  disabled         = FALSE;
    gboolean  skip_end_of_line = FALSE;
    int       ret = 0;

    name = (gchar *)g_malloc(name_len + 1);
    filter_exp = (gchar *)g_malloc(filter_exp_len + 1);

    while (1) {

        if (skip_end_of_line) {
            do {
                c = ws_getc_unlocked(f);
            } while (c != EOF && c != '\n');
            if (c == EOF)
                break;
            disabled = FALSE;
            skip_end_of_line = FALSE;
        }

        while ((c = ws_getc_unlocked(f)) != EOF && g_ascii_isspace(c)) {
            if (c == '\n') {
                continue;
            }
        }

        if (c == EOF)
            break;

        if (c == '!') {
            disabled = TRUE;
            continue;
        }

        /* skip # comments and invalid lines */
        if (c != '@') {
            skip_end_of_line = TRUE;
            continue;
        }

        /* we get the @ delimiter.
         * Format is:
         * @name@filter expression@[background r,g,b][foreground r,g,b]
         */

        /* retrieve name */
        i = 0;
        while (1) {
            c = ws_getc_unlocked(f);
            if (c == EOF || c == '@')
                break;
            if (i >= name_len) {
                /* buffer isn't long enough; double its length.*/
                name_len *= 2;
                name = (gchar *)g_realloc(name, name_len + 1);
            }
            name[i++] = c;
        }
        name[i] = '\0';

        if (c == EOF) {
            break;
        } else if (i == 0) {
            skip_end_of_line = TRUE;
            continue;
        }

        /* retrieve filter expression */
        i = 0;
        while (1) {
            c = ws_getc_unlocked(f);
            if (c == EOF || c == '@')
                break;
            if (i >= filter_exp_len) {
                /* buffer isn't long enough; double its length.*/
                filter_exp_len *= 2;
                filter_exp = (gchar *)g_realloc(filter_exp, filter_exp_len + 1);
            }
            filter_exp[i++] = c;
        }
        filter_exp[i] = '\0';

        if (c == EOF) {
            break;
        } else if (i == 0) {
            skip_end_of_line = TRUE;
            continue;
        }

        /* retrieve background and foreground colors */
        if (fscanf(f,"[%hu,%hu,%hu][%hu,%hu,%hu]",
                   &bg_r, &bg_g, &bg_b, &fg_r, &fg_g, &fg_b) == 6) {

            /* we got a complete color filter */

            color_t bg_color, fg_color;
            color_filter_t *colorf;
            dfilter_t *temp_dfilter = NULL;
            gchar *local_err_msg = NULL;

            if (!disabled && !dfilter_compile(filter_exp, &temp_dfilter, &local_err_msg)) {
                ws_g_warning("Could not compile \"%s\" in colorfilters file \"%s\".\n%s",
                          name, path, local_err_msg);
                g_free(local_err_msg);
                prefs.unknown_colorfilters = TRUE;

                /* skip_end_of_line = TRUE; */
                disabled = TRUE;
            }

            fg_color.red = fg_r;
            fg_color.green = fg_g;
            fg_color.blue = fg_b;

            bg_color.red = bg_r;
            bg_color.green = bg_g;
            bg_color.blue = bg_b;

            colorf = color_filter_new(name, filter_exp, &bg_color,
                                      &fg_color, disabled);
            if(user_data == &color_filter_list) {
                GSList **cfl = (GSList **)user_data;

                /* internal call */
                colorf->c_colorfilter = temp_dfilter;
                *cfl = g_slist_append(*cfl, colorf);
            } else {
                /* external call */
                /* just editing, don't need the compiled filter */
                dfilter_free(temp_dfilter);
                add_cb(colorf, user_data);
            }
        }    /* if sscanf */

        skip_end_of_line = TRUE;
    }

    if (ferror(f))
        ret = errno;

    g_free(name);
    g_free(filter_exp);
    return ret;
}
Iax2AnalysisDialog::Iax2AnalysisDialog(QWidget &parent, CaptureFile &cf) :
    WiresharkDialog(parent, cf),
    ui(new Ui::Iax2AnalysisDialog),
    port_src_fwd_(0),
    port_dst_fwd_(0),
    port_src_rev_(0),
    port_dst_rev_(0)
{
    ui->setupUi(this);
    setWindowSubtitle(tr("IAX2 Stream Analysis"));

    // XXX Use recent settings instead
    resize(parent.width() * 4 / 5, parent.height() * 4 / 5);
    ui->progressFrame->hide();

    stream_ctx_menu_.addAction(ui->actionGoToPacket);
    stream_ctx_menu_.addAction(ui->actionNextProblem);
    stream_ctx_menu_.addSeparator();
    stream_ctx_menu_.addAction(ui->actionSaveAudio);
    stream_ctx_menu_.addAction(ui->actionSaveForwardAudio);
    stream_ctx_menu_.addAction(ui->actionSaveReverseAudio);
    stream_ctx_menu_.addSeparator();
    stream_ctx_menu_.addAction(ui->actionSaveCsv);
    stream_ctx_menu_.addAction(ui->actionSaveForwardCsv);
    stream_ctx_menu_.addAction(ui->actionSaveReverseCsv);
    stream_ctx_menu_.addSeparator();
    stream_ctx_menu_.addAction(ui->actionSaveGraph);
    ui->forwardTreeWidget->installEventFilter(this);
    ui->forwardTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->forwardTreeWidget, SIGNAL(customContextMenuRequested(QPoint)),
                SLOT(showStreamMenu(QPoint)));
    ui->reverseTreeWidget->installEventFilter(this);
    ui->reverseTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->reverseTreeWidget, SIGNAL(customContextMenuRequested(QPoint)),
                SLOT(showStreamMenu(QPoint)));
    connect(ui->streamGraph, SIGNAL(mousePress(QMouseEvent*)),
            this, SLOT(graphClicked(QMouseEvent*)));

    graph_ctx_menu_.addAction(ui->actionSaveGraph);

    QStringList header_labels;
    for (int i = 0; i < ui->forwardTreeWidget->columnCount(); i++) {
        header_labels << ui->forwardTreeWidget->headerItem()->text(i);
    }
    ui->reverseTreeWidget->setHeaderLabels(header_labels);

    memset(&src_fwd_, 0, sizeof(address));
    memset(&dst_fwd_, 0, sizeof(address));
    memset(&src_rev_, 0, sizeof(address));
    memset(&dst_rev_, 0, sizeof(address));

    QList<QCheckBox *> graph_cbs = QList<QCheckBox *>()
            << ui->fJitterCheckBox << ui->fDiffCheckBox
            << ui->rJitterCheckBox << ui->rDiffCheckBox;

    for (int i = 0; i < num_graphs_; i++) {
        QCPGraph *graph = ui->streamGraph->addGraph();
        graph->setPen(QPen(ColorUtils::graph_colors_[i]));
        graph->setName(graph_cbs[i]->text());
        graphs_ << graph;
        graph_cbs[i]->setChecked(true);
        graph_cbs[i]->setIcon(StockIcon::colorIcon(ColorUtils::graph_colors_[i], QPalette::Text));
    }
    ui->streamGraph->xAxis->setLabel("Arrival Time");
    ui->streamGraph->yAxis->setLabel("Value (ms)");

    // We keep our temp files open for the lifetime of the dialog. The GTK+
    // UI opens and closes at various points.
    QString tempname = QString("%1/wireshark_iax2_f").arg(QDir::tempPath());
    fwd_tempfile_ = new QTemporaryFile(tempname, this);
    fwd_tempfile_->open();
    tempname = QString("%1/wireshark_iax2_r").arg(QDir::tempPath());
    rev_tempfile_ = new QTemporaryFile(tempname, this);
    rev_tempfile_->open();

    if (fwd_tempfile_->error() != QFile::NoError || rev_tempfile_->error() != QFile::NoError) {
        err_str_ = tr("Unable to save RTP data.");
        ui->actionSaveAudio->setEnabled(false);
        ui->actionSaveForwardAudio->setEnabled(false);
        ui->actionSaveReverseAudio->setEnabled(false);
    }

    QMenu *save_menu = new QMenu();
    save_menu->addAction(ui->actionSaveAudio);
    save_menu->addAction(ui->actionSaveForwardAudio);
    save_menu->addAction(ui->actionSaveReverseAudio);
    save_menu->addSeparator();
    save_menu->addAction(ui->actionSaveCsv);
    save_menu->addAction(ui->actionSaveForwardCsv);
    save_menu->addAction(ui->actionSaveReverseCsv);
    save_menu->addSeparator();
    save_menu->addAction(ui->actionSaveGraph);
    ui->buttonBox->button(QDialogButtonBox::Save)->setMenu(save_menu);

    const gchar *filter_text = "iax2 && (ip || ipv6)";
    dfilter_t *sfcode;
    gchar *err_msg;

    if (!dfilter_compile(filter_text, &sfcode, &err_msg)) {
        QMessageBox::warning(this, tr("No IAX2 packets found"), QString("%1").arg(err_msg));
        g_free(err_msg);
        close();
    }

    if (!cap_file_.capFile() || !cap_file_.capFile()->current_frame) close();

    frame_data *fdata = cap_file_.capFile()->current_frame;

    if (!cf_read_record(cap_file_.capFile(), fdata)) close();

    epan_dissect_t edt;

    epan_dissect_init(&edt, cap_file_.capFile()->epan, TRUE, FALSE);
    epan_dissect_prime_dfilter(&edt, sfcode);
    epan_dissect_run(&edt, cap_file_.capFile()->cd_t, &cap_file_.capFile()->phdr,
                     frame_tvbuff_new_buffer(fdata, &cap_file_.capFile()->buf), fdata, NULL);

    // This shouldn't happen (the menu item should be disabled) but check anyway
    if (!dfilter_apply_edt(sfcode, &edt)) {
        epan_dissect_cleanup(&edt);
        dfilter_free(sfcode);
        err_str_ = tr("Please select an IAX2 packet");
        updateWidgets();
        return;
    }

    dfilter_free(sfcode);

    /* ok, it is a IAX2 frame, so let's get the ip and port values */
    COPY_ADDRESS(&(src_fwd_), &(edt.pi.src));
    COPY_ADDRESS(&(dst_fwd_), &(edt.pi.dst));
    port_src_fwd_ = edt.pi.srcport;
    port_dst_fwd_ = edt.pi.destport;

    /* assume the inverse ip/port combination for the reverse direction */
    COPY_ADDRESS(&(src_rev_), &(edt.pi.dst));
    COPY_ADDRESS(&(dst_rev_), &(edt.pi.src));
    port_src_rev_ = edt.pi.destport;
    port_dst_rev_ = edt.pi.srcport;

#if 0
    /* check if it is Voice or MiniPacket */
    bool ok;
    getIntFromProtoTree(edt.tree, "iax2", "iax2.call", &ok);
    if (!ok) {
        err_str_ = tr("Please select an IAX2 packet.");
        updateWidgets();
        return;
    }
#endif

#ifdef IAX2_RTP_STREAM_CHECK
    rtpstream_tapinfot tapinfo;

    /* Register the tap listener */
    memset(&tapinfo, 0, sizeof(rtpstream_tapinfot));
    tapinfo.tap_data = this;
    tapinfo.mode = TAP_ANALYSE;

//    register_tap_listener_rtp_stream(&tapinfo, NULL);
    /* Scan for RTP streams (redissect all packets) */
    rtpstream_scan(&tapinfo, cap_file_.capFile(), NULL);

    int num_streams = 0;
    GList *filtered_list = NULL;
    for (GList *strinfo_list = g_list_first(tapinfo.strinfo_list); strinfo_list; strinfo_list = g_list_next(strinfo_list)) {
        rtp_stream_info_t * strinfo = (rtp_stream_info_t*)(strinfo_list->data);
                 << address_to_qstring(&strinfo->dest_addr) << address_to_qstring(&src_rev_) << address_to_qstring(&dst_rev_);
        if (ADDRESSES_EQUAL(&(strinfo->src_addr), &(src_fwd_))
            && (strinfo->src_port == port_src_fwd_)
            && (ADDRESSES_EQUAL(&(strinfo->dest_addr), &(dst_fwd_)))
            && (strinfo->dest_port == port_dst_fwd_))
        {
            ++num_streams;
            filtered_list = g_list_prepend(filtered_list, strinfo);
        }

        if (ADDRESSES_EQUAL(&(strinfo->src_addr), &(src_rev_))
            && (strinfo->src_port == port_src_rev_)
            && (ADDRESSES_EQUAL(&(strinfo->dest_addr), &(dst_rev_)))
            && (strinfo->dest_port == port_dst_rev_))
        {
            ++num_streams;
            filtered_list = g_list_append(filtered_list, strinfo);
        }
    }
Example #23
0
int
main(int argc, char **argv)
{
	char		*init_progfile_dir_error;
	char		*text;
	dfilter_t	*df;
	gchar		*err_msg;

	/*
	 * Get credential information for later use.
	 */
	init_process_policies();

	/*
	 * Attempt to get the pathname of the directory containing the
	 * executable file.
	 */
	init_progfile_dir_error = init_progfile_dir(argv[0], main);
	if (init_progfile_dir_error != NULL) {
		fprintf(stderr, "dftest: Can't get pathname of directory containing the dftest program: %s.\n",
			init_progfile_dir_error);
		g_free(init_progfile_dir_error);
	}

	init_report_message(failure_warning_message, failure_warning_message,
			    open_failure_message, read_failure_message,
			    write_failure_message);

	timestamp_set_type(TS_RELATIVE);
	timestamp_set_seconds_type(TS_SECONDS_DEFAULT);

#ifdef HAVE_PLUGINS
	/* Register all the plugin types we have. */
	epan_register_plugin_types(); /* Types known to libwireshark */

	/* Scan for plugins.  This does *not* call their registration routines;
	   that's done later. */
	scan_plugins(REPORT_LOAD_FAILURE);
#endif

	wtap_init();

	/* Register all dissectors; we must do this before checking for the
	   "-g" flag, as the "-g" flag dumps a list of fields registered
	   by the dissectors, and we must do it before we read the preferences,
	   in case any dissectors register preferences. */
	if (!epan_init(register_all_protocols, register_all_protocol_handoffs,
	    NULL, NULL))
		return 2;

	/* set the c-language locale to the native environment. */
	setlocale(LC_ALL, "");

	/* Load libwireshark settings from the current profile. */
	epan_load_settings();

	/* notify all registered modules that have had any of their preferences
	changed either from one of the preferences file or from the command
	line that its preferences have changed. */
	prefs_apply_all();

	/* Check for filter on command line */
	if (argc <= 1) {
		fprintf(stderr, "Usage: dftest <filter>\n");
		exit(1);
	}

	/* Get filter text */
	text = get_args_as_string(argc, argv, 1);

	printf("Filter: \"%s\"\n", text);

	/* Compile it */
	if (!dfilter_compile(text, &df, &err_msg)) {
		fprintf(stderr, "dftest: %s\n", err_msg);
		g_free(err_msg);
		epan_cleanup();
		exit(2);
	}

	printf("\n");

	if (df == NULL)
		printf("Filter is empty\n");
	else
		dfilter_dump(df);

	dfilter_free(df);
	epan_cleanup();
	exit(0);
}