예제 #1
0
/* this function removes a tap listener
 */
void
remove_tap_listener(void *tapdata)
{
	tap_listener_t *tl=NULL,*tl2;

	if(!tap_listener_queue){
		return;
	}

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

	if(tl){
		if(tl->code){
			dfilter_free(tl->code);
		}
		g_free(tl);
	}

	return;
}
예제 #2
0
파일: tap.c 프로젝트: alagoutte/wireshark
/* 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);
				err_msg = NULL;
				/* Not valid, make a dfilter matching no packets */
				if (!dfilter_compile("frame.number == 0", &code, &err_msg))
					g_free(err_msg);
			}
		}
		tl->code=code;
	}
}
예제 #3
0
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);
}
예제 #4
0
파일: fileh.cpp 프로젝트: ottimo/stress
void CaptureFile::resetState() {
    /* Die if we're in the middle of reading a file. */
    //	g_assert(state != FILE_READ_IN_PROGRESS); //FIXME controllo?

    if (wth) {
        wtap_close(wth);
        wth = NULL;
    }


#if GLIB_CHECK_VERSION(2,10,0)
    if (plist != NULL)
        g_slice_free_chain(frame_data, plist, next);
#else
    if (plist_chunk != NULL) {
        frame_data *fdata = plist;
        while (fdata) {
            g_strfreev(fdata->col_expr.col_expr);
            g_strfreev(fdata->col_expr.col_expr_val);
            fdata = fdata->next;
        }
        /* memory chunks have been deprecated in favor of the slice allocator,
         * which has been added in 2.10
         */
        g_mem_chunk_destroy(plist_chunk);
        plist_chunk = NULL;
    }
#endif
    if (rfcode != NULL) {
        dfilter_free(rfcode);
        rfcode = NULL;
    }
    plist = NULL;
    plist_end = NULL;
    //	cf_unselect_packet(cf);	/* nothing to select */
    //    first_displayed = NULL;
    //    last_displayed = NULL;
    //
    //    /* No frame selected, no field in that frame selected. */
    //    current_frame = NULL;
    //    current_row = 0;
    //    finfo_selected = NULL;

    /* Clear the packet list. */
    //	packet_list_freeze();
    //	packet_list_clear();
    //	packet_list_thaw();

    f_datalen = 0;
    count = 0;
    //nstime_set_zero(&elapsed_time);

    //  reset_tap_listeners();

    /* We have no file open. */
    state = FILE_CLOSED;

    //fileset_file_closed();
}
예제 #5
0
/* 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;
}
예제 #6
0
/* delete the specified filter */
void
color_filter_delete(color_filter_t *colorf)
{
    if (colorf->filter_name != NULL)
        g_free(colorf->filter_name);
    if (colorf->filter_text != NULL)
        g_free(colorf->filter_text);
    if (colorf->c_colorfilter != NULL)
        dfilter_free(colorf->c_colorfilter);
    g_free(colorf);
}
예제 #7
0
파일: tap.c 프로젝트: alagoutte/wireshark
static void
free_tap_listener(volatile tap_listener_t *tl)
{
	if(!tl)
		return;
	dfilter_free(tl->code);
	g_free(tl->fstring);
DIAG_OFF(cast-qual)
	g_free((gpointer)tl);
DIAG_ON(cast-qual)
}
예제 #8
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 */
}
예제 #9
0
파일: tap.c 프로젝트: linshimiao/wireshark
/* 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);
}
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);
    }
}
예제 #12
0
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);
}
예제 #13
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);
}
예제 #14
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;
}
예제 #15
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;
}
예제 #16
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;
}
예제 #17
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;
}
예제 #18
0
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);
        }
    }
예제 #19
0
파일: dftest.c 프로젝트: gnlsw/wireshark
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);
}