aboutsummaryrefslogtreecommitdiffstats
path: root/ui/qt/capture_file_dialog.cpp
blob: cdbe92cea1984438343aa06e390f9c50204ac068 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/* capture_file_dialog.cpp
 *
 * $Id$
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <glib.h>

#include <wiretap/wtap.h>

#include "capture_file_dialog.h"

#ifdef Q_WS_WIN
#include <windows.h>
#include "ui/win32/file_dlg_win32.h"
#endif

#include <errno.h>
#include "../../epan/addr_resolv.h"
#include "../../epan/prefs.h"
#include "../../epan/filesystem.h"
#include "../../epan/nstime.h"
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QCheckBox>
#include <QFileInfo>

#include <QDebug>

#ifdef Q_WS_WIN
// All of these routines are required by file_dlg_win32.c.
// We don't yet have a good place for them so we'll add them as stubs here.

extern "C" {

// From gtk/capture_dlg.[ch]
/* capture start confirmed by "Save unsaved capture", so do it now */
extern void capture_start_confirmed(void) {
}

// From gtk/drag_and_drop.[ch]
/** Open a new file coming from drag and drop.
 * @param cf_names_freeme the selection data reported from GTK
 */
extern void dnd_open_file_cmd(gchar *cf_names_freeme) {
    Q_UNUSED(cf_names_freeme);
}

// From gtk/menus.h & main_menubar.c
/** User pushed a recent file submenu item.
 *
 * @param widget parent widget
 */
extern void menu_open_recent_file_cmd(gpointer action){
    Q_UNUSED(action)
}

/** One of the name resolution menu items changed. */
extern void menu_name_resolution_changed(void) {

}

// From gtk/export_sslkeys.[ch]
/** Callback for "Export SSL Session Keys" operation.
 *
 * @param w unused
 * @param data unused
 */
extern void savesslkeys_cb(gpointer * w, gpointer data) {
    Q_UNUSED(w);
    Q_UNUSED(data);
}

/** Dump the SSL Session Keys to a StringInfo string
 *
 * @param session_hash contains all the SSL Session Keys
 */
extern gpointer ssl_export_sessions(GHashTable *session_hash) {
    Q_UNUSED(session_hash);
    return NULL;
}

// From gtk/help_dlg.[ch]
/** Open a specific topic (create a "Help" dialog box or open a webpage).
 *
 * @param widget parent widget (unused)
 * @param topic the topic to display
 */
extern void topic_cb(gpointer *widget, int topic) {
    Q_UNUSED(widget);
    Q_UNUSED(topic);
}

}
// End stub routines
#endif // Q_WS_WIN

CaptureFileDialog::CaptureFileDialog(QWidget *parent, QString &display_filter) :
    QFileDialog(parent), display_filter_(display_filter)
{
#if !defined(Q_WS_WIN)

    // Add extra widgets
    // http://qt-project.org/faq/answer/how_can_i_add_widgets_to_my_qfiledialog_instance
    setOption(QFileDialog::DontUseNativeDialog, true);
    QGridLayout *fd_grid = qobject_cast<QGridLayout*>(layout());
    QHBoxLayout *h_box = new QHBoxLayout();

    fd_grid->addWidget(new QLabel(tr("Display Filter:")), fd_grid->rowCount(), 0, 1, 1);

    display_filter_edit_ = new DisplayFilterEdit(this, true);
    display_filter_edit_->setText(display_filter_);
    fd_grid->addWidget(display_filter_edit_, fd_grid->rowCount() - 1, 1, 1, 1);

    fd_grid->addLayout(h_box, fd_grid->rowCount(), 1, 1, -1);

    // Left and right boxes for controls and preview
    h_box->addLayout(&left_v_box_);
    h_box->addLayout(&right_v_box_);


#else // Q_WS_WIN
    merge_type_ = 0;
#endif // Q_WS_WIN
}

void CaptureFileDialog::addPreview(QVBoxLayout &v_box) {
    QGridLayout *preview_grid = new QGridLayout();
    QLabel *lbl;

    preview_labels_.clear();
    v_box.addLayout(preview_grid);

    preview_grid->setColumnStretch(0, 0);
    preview_grid->setColumnStretch(1, 10);

    lbl = new QLabel("Format:");
    preview_grid->addWidget(lbl, 0, 0);
    preview_grid->addWidget(&preview_format_, 0, 1);
    preview_labels_ << lbl << &preview_format_;

    lbl = new QLabel("Size:");
    preview_grid->addWidget(lbl, 1, 0);
    preview_grid->addWidget(&preview_size_, 1, 1);
    preview_labels_ << lbl << &preview_size_;

    lbl = new QLabel("Packets:");
    preview_grid->addWidget(lbl, 2, 0);
    preview_grid->addWidget(&preview_packets_, 2, 1);
    preview_labels_ << lbl << &preview_packets_;

    lbl = new QLabel("First Packet:");
    preview_grid->addWidget(lbl, 3, 0);
    preview_grid->addWidget(&preview_first_, 3, 1);
    preview_labels_ << lbl << &preview_first_;

    lbl = new QLabel("Elapsed Time:");
    preview_grid->addWidget(lbl, 4, 0);
    preview_grid->addWidget(&preview_elapsed_, 4, 1);
    preview_labels_ << lbl << &preview_elapsed_;

    connect(this, SIGNAL(currentChanged(const QString &)), this, SLOT(preview(const QString &)));

    preview("");
}

void CaptureFileDialog::addMergeControls(QVBoxLayout &v_box) {

    merge_prepend_.setText("Prepend packets");
    merge_prepend_.setToolTip("Insert packets from the selected file before the current file. Packet timestamps will be ignored.");
    v_box.addWidget(&merge_prepend_);

    merge_chrono_.setText("Merge chronologically");
    merge_chrono_.setToolTip("Insert packets in chronological order.");
    merge_chrono_.setChecked(true);
    v_box.addWidget(&merge_chrono_);

    merge_append_.setText("Append packets");
    merge_append_.setToolTip("Insert packets from the selected file after the current file. Packet timestamps will be ignored.");
    v_box.addWidget(&merge_append_);
}

// You have to use open, merge, saveAs, or exportPackets. We should
// probably just make each type a subclass.
int CaptureFileDialog::exec() {
    return QDialog::Rejected;
}

QString CaptureFileDialog::fileType(int ft, bool extension_globs)
{
    QString filter;
    GSList *extensions_list, *extension;

    filter = wtap_file_type_string(ft);

    if (!extension_globs)
        return filter;

    filter += " (";

    extensions_list = wtap_get_file_extensions_list(ft, TRUE);
    if (extensions_list == NULL) {
        /* This file type doesn't have any particular extension
           conventionally used for it, so we'll just use "*.*"
           as the pattern; on Windows, that matches all file names
           - even those with no extension -  so we don't need to
           worry about compressed file extensions.  (It does not
           do so on UN*X; the right pattern on UN*X would just
           be "*".) */
           filter += "*.*";
    } else {
        /* Construct the list of patterns. */
        for (extension = extensions_list; extension != NULL;
             extension = g_slist_next(extension)) {
            if (!filter.endsWith('('))
                filter += ' ';
            filter += "*.";
            filter += (char *)extension->data;
        }
        wtap_free_file_extensions_list(extensions_list);
    }
    filter += ')';
    return filter;
    /* XXX - does QStringList's destructor destroy the strings in the list? */
}

QStringList CaptureFileDialog::buildFileOpenTypeList() {
    QStringList filters;
    int   ft;

    /* Add the "All Files" entry. */
    filters << QString(tr("All Files (*.*)"));

    /* Include all the file types Wireshark supports. */
    for (ft = 0; ft < WTAP_NUM_FILE_TYPES; ft++) {
        if (ft == WTAP_FILE_UNKNOWN)
            continue;  /* not a real file type */

        filters << fileType(ft);
    }

    return filters;
}


// Windows
#ifdef Q_WS_WIN
int CaptureFileDialog::open(QString &file_name) {
    GString *fname = g_string_new(file_name.toUtf8().constData());
    GString *dfilter = g_string_new(display_filter_.toUtf8().constData());
    gboolean wof_status;

    wof_status = win32_open_file(parentWidget()->effectiveWinId(), fname, dfilter);
    file_name.append(QString::fromUtf8(fname->str));
    display_filter_.clear();
    display_filter_.append(QString::fromUtf8(dfilter->str));

    g_string_free(fname, TRUE);
    g_string_free(dfilter, TRUE);

    return (int) wof_status;
}

int CaptureFileDialog::merge(QString &file_name) {
    GString *fname = g_string_new(file_name.toUtf8().constData());
    GString *dfilter = g_string_new(display_filter_.toUtf8().constData());
    gboolean wmf_status;

    wmf_status = win32_merge_file(parentWidget()->effectiveWinId(), fname, dfilter, &merge_type_);
    file_name.append(QString::fromUtf8(fname->str));
    display_filter_.clear();
    display_filter_.append(QString::fromUtf8(dfilter->str));

    g_string_free(fname, TRUE);
    g_string_free(dfilter, TRUE);

    return (int) wmf_status;
}

int CaptureFileDialog::mergeType() {
    return merge_type_;
}

#else // not Q_WS_WINDOWS
int CaptureFileDialog::selectedFileType() {
    return type_hash_.value(selectedNameFilter(), -1);
}

void CaptureFileDialog::addDisplayFilterEdit() {

}

void CaptureFileDialog::addResolutionControls(QVBoxLayout &v_box) {
    mac_res_.setText(tr("&MAC name resolution"));
    mac_res_.setChecked(gbl_resolv_flags.mac_name);
    v_box.addWidget(&mac_res_);

    transport_res_.setText(tr("&Transport name resolution"));
    transport_res_.setChecked(gbl_resolv_flags.transport_name);
    v_box.addWidget(&transport_res_);

    network_res_.setText(tr("&Network name resolution"));
    network_res_.setChecked(gbl_resolv_flags.network_name);
    v_box.addWidget(&network_res_);

    external_res_.setText(tr("&External name resolver"));
    external_res_.setChecked(gbl_resolv_flags.use_external_net_name_resolver);
    v_box.addWidget(&external_res_);
}

int CaptureFileDialog::open(QString &file_name) {
    setWindowTitle(tr("Wireshark: Open Capture File"));
    setNameFilters(buildFileOpenTypeList());
    setFileMode(QFileDialog::ExistingFile);

    file_name.clear();
    display_filter_.clear();

    addResolutionControls(left_v_box_);
    addPreview(right_v_box_);

    // Grow the dialog to account for the extra widgets.
    resize(width(), height() + left_v_box_.minimumSize().height() + display_filter_edit_->minimumSize().height());

    if (!file_name.isEmpty()) {
        selectFile(file_name);
    }

    if (QFileDialog::exec() && selectedFiles().length() > 0) {
        file_name.append(selectedFiles()[0]);
        display_filter_.append(display_filter_edit_->text());

        gbl_resolv_flags.mac_name = mac_res_.isChecked();
        gbl_resolv_flags.transport_name = transport_res_.isChecked();
        gbl_resolv_flags.network_name = network_res_.isChecked();
        gbl_resolv_flags.use_external_net_name_resolver = external_res_.isChecked();

        return QDialog::Accepted;
    } else {
        return QDialog::Rejected;
    }
}

int CaptureFileDialog::merge(QString &file_name) {
    setWindowTitle(tr("Wireshark: Merge Capture File"));
    setNameFilters(buildFileOpenTypeList());
    setFileMode(QFileDialog::ExistingFile);

    file_name.clear();
    display_filter_.clear();

    addMergeControls(left_v_box_);
    addPreview(right_v_box_);

    // Grow the dialog to account for the extra widgets.
    resize(width(), height() + right_v_box_.minimumSize().height() + display_filter_edit_->minimumSize().height());

    if (QFileDialog::exec() && selectedFiles().length() > 0) {
        file_name.append(selectedFiles()[0]);
        display_filter_.append(display_filter_edit_->text());

        return QDialog::Accepted;
    } else {
        return QDialog::Rejected;
    }
}

QStringList CaptureFileDialog::buildFileSaveAsTypeList(capture_file *cf, bool must_support_comments) {
    QStringList filters;
    GArray *savable_file_types;
    guint i;
    int ft;
    int default_ft = -1;

    type_hash_.clear();
    savable_file_types = wtap_get_savable_file_types(cf->cd_t, cf->linktypes);

    if (savable_file_types != NULL) {
        QString file_type;
        /* OK, we have at least one file type we can save this file as.
           (If we didn't, we shouldn't have gotten here in the first
           place.)  Add them all to the combo box.  */
        for (i = 0; i < savable_file_types->len; i++) {
            ft = g_array_index(savable_file_types, int, i);
            if (must_support_comments) {
                if (ft != WTAP_FILE_PCAPNG)
                    continue;
            }
            if (default_ft == -1)
                default_ft = ft; /* first file type is the default */
            file_type = fileType(ft, false);
            filters << file_type;
            type_hash_[file_type] = ft;
        }
        g_array_free(savable_file_types, TRUE);
    }

    return filters;
}

int CaptureFileDialog::mergeType() {
    if (merge_prepend_.isChecked())
        return -1;
    else if (merge_append_.isChecked())
        return 1;

    return 0;
}
#endif // Q_WS_WINDOWS


/* do a preview run on the currently selected capture file */
void CaptureFileDialog::preview(const QString & path)
{
    wtap        *wth;
    int          err = 0;
    gchar       *err_info;
    gint64       data_offset;
    const struct wtap_pkthdr *phdr;
    double       start_time = 0; /* seconds, with nsec resolution */
    double       stop_time = 0;  /* seconds, with nsec resolution */
    double       cur_time;
    unsigned int packets = 0;
    bool         timed_out = FALSE;
    time_t       time_preview;
    time_t       time_current;
    time_t       ti_time;
    struct tm   *ti_tm;
    unsigned int elapsed_time;

    // Follow the same steps as ui/win32/file_dlg_win32.c

    foreach (QLabel *lbl, preview_labels_) {
        lbl->setEnabled(false);
    }

    preview_format_.setText(tr("-"));
    preview_size_.setText(tr("-"));
    preview_packets_.setText(tr("-"));
    preview_first_.setText(tr("-"));
    preview_elapsed_.setText(tr("-"));

    if (path.length() < 1) {
        return;
    }

    if (test_for_directory(path.toUtf8().data()) == EISDIR) {
        preview_format_.setText(tr("directory"));
        return;
    }

    wth = wtap_open_offline(path.toUtf8().data(), &err, &err_info, TRUE);
    if (wth == NULL) {
        if(err == WTAP_ERR_FILE_UNKNOWN_FORMAT) {
            preview_format_.setText(tr("unknown file format"));
        } else {
            preview_format_.setText(tr("error opening file"));
        }
        return;
    }

    // Success!
    foreach (QLabel *lbl, preview_labels_) {
        lbl->setEnabled(true);
    }

    // Format
    preview_format_.setText(QString::fromUtf8(wtap_file_type_string(wtap_file_type(wth))));

    // Size
    preview_size_.setText(QString("%1 bytes").arg(wtap_file_size(wth, &err)));

    time(&time_preview);
    while ( (wtap_read(wth, &err, &err_info, &data_offset)) ) {
        phdr = wtap_phdr(wth);
        cur_time = wtap_nstime_to_sec(&phdr->ts);
        if(packets == 0) {
            start_time = cur_time;
            stop_time = cur_time;
        }
        if (cur_time < start_time) {
            start_time = cur_time;
        }
        if (cur_time > stop_time){
            stop_time = cur_time;
        }

        packets++;
        if(packets%1000 == 0) {
            /* do we have a timeout? */
            time(&time_current);
            if(time_current-time_preview >= (time_t) prefs.gui_fileopen_preview) {
                timed_out = TRUE;
                break;
            }
        }
    }

    if(err != 0) {
        preview_packets_.setText(QString("error after reading %1 packets").arg(packets));
        return;
    }

    // Packet count
    if(timed_out) {
        preview_packets_.setText(QString("more than %1 (preview timeout)").arg(packets));
    } else {
        preview_packets_.setText(QString("%1").arg(packets));
    }

    // First packet
    ti_time = (long)start_time;
    ti_tm = localtime( &ti_time );
    if(ti_tm) {
        preview_first_.setText(QString().sprintf(
                 "%04d-%02d-%02d %02d:%02d:%02d",
                 ti_tm->tm_year + 1900,
                 ti_tm->tm_mon + 1,
                 ti_tm->tm_mday,
                 ti_tm->tm_hour,
                 ti_tm->tm_min,
                 ti_tm->tm_sec
                 ));
    } else {
        preview_first_.setText(tr("?"));
    }

    // Elapsed time
    elapsed_time = (unsigned int)(stop_time-start_time);
    if(timed_out) {
        preview_elapsed_.setText(tr("unknown"));
    } else if(elapsed_time/86400) {
        preview_elapsed_.setText(QString().sprintf("%02u days %02u:%02u:%02u",
                elapsed_time/86400, elapsed_time%86400/3600, elapsed_time%3600/60, elapsed_time%60));
    } else {
        preview_elapsed_.setText(QString().sprintf("%02u:%02u:%02u",
                elapsed_time%86400/3600, elapsed_time%3600/60, elapsed_time%60));
    }

    wtap_close(wth);
}

/*
 * Editor modelines
 *
 * Local Variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * ex: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */