Wireshark Source Code Analysis

Source: Internet
Author: User
Tags gtk visual studio

It's not that I don't want to answer your questions, folks. Yes, I don't know either. Not misleading. I hope everyone helps each other. See if you can help those small friends who ask questions to reply.

These are reproduced, if there is no way, you can open the link to the original author where to ask the question to try ...



After several attempts, finally on the Windows successfully compiled Wireshark source code, but not with the following this step, but very much the same, my is vs2005, so use: http://blog.csdn.net/alexander_vc/ Method of article/details/6198836. 1.2.7 version of Wireshark capture_if_details_dlg_win32.c has a bug in vs2005, need to download the updated Wireshark version, and replace the file. See Wireshark's Wireshark Bug database–bug 3439


Note: 1.python to use 2.4--2.6 version

2.Cygwin installation to install the library described in the article

3. If the execution of the command, always nmake to report all kinds of errors, please repeatedly check your Wireshark directory config.nmake file configuration is correct.


It was compiled successfully with vs2005,vs2010. Have to say this depends on the character, try more, there are always ways.


Original address: Http://blog.sina.com.cn/xianjiaotonguniversity
compiling the Wireshark source code on Windows

The following software is required during the compilation process: Visualstudio,python,cygwin and Wireshark source code.

1. Visual Studio

I am using the Visual Studio 2008 version.

2. Python

Download install Python, from 2.4–2.6 should all be possible, I use version 2.6. Python is used primarily during the compilation process.

3. Cygwin

Go to Cygwin download the latest version of the installation, and then start the installation, the entire installation process is online installation, especially note that the following libraries must be installed, or the compilation will not be completed successfully:

Archive/unzip
devel/bison
devel/flex
interpreters/perl
utils/patch
web/wget

4. Download Wireshark source code & Edit Config.nmake

Enter this URL, http://www.wireshark.org/download/src/all-versions/, download Wireshark source code from above, here, it is worth mentioning, it is best to download the source code in the SVN given in the page, Ensures that the code is absolutely up-to-date.

After the download is complete, the Config.nmake is opened in the Wireshark directory and some settings need to be set before the compilation can begin.

(1) Wireshark_libs, set the directory in which the libraries needed to compile the WIRESHARK are located, by default.
(2) Program_files, set the native program installation directory, default.
(3) Msvc_variant, because I use VS2008 compile, so do not modify here. If you are using a different version of VS, remove the # in front of the corresponding line and add the # of the remaining lines. For example, if you are using VS2005, the # before the line with the value MSVC2005 is removed, and the rest of the msvc_variant entries are all added with the # comment out.
(4) Cygwin_path, set it to the bin directory of CYGWIN, such as D:\cygwin\bin.
(5)Msvcr_dll, if the VS is installed in the D drive, please use the absolute path in the corresponding place, and do not modify the previous program_files, otherwise there will be unexpected errors.

5. Compiling Wireshark

Use the VS2008 installation of the VS2008 command prompt to enter or through CMD to enter, then run the VC under the Vcvars32.bat, or to drag vcvars32.bat to the Command window, and then enter the line. Then go in the Wireshark directory, first check by the following command:

Nmake-f Makefile.nmake verify_tools
Get the following information:






I forgot the screenshot, this is copy other people's picture, but I like his basic, out of the above copyright information is Chinese, and the copyright information under an error, said that the contents of the C:\wireshark-win32-libs\current_tag.txt should be outside of 2011-06-27, the others are the same. However, this error does not have to be managed and does not affect compilation.
6. The implementation of Nmake–f Makefile.nmake Setup

obtains a lot of information, and finally reads as follows:



7. Perform the next nmake–f makefile.nmake Distclean

8. Execute nmake–f Makefile.nmake

All this process takes 10 minutes, and here the compilation is complete.


Wireshark Source Code Analysis report because the project at hand needs to identify the application layer protocol, so think of Wireshark, intends to integrate Wireshark protocol analysis code in the project. On the official website under the latest version of the Wireshark source code, my goodness, more than 200 m, so many code files how to see. On the internet for a long time, hoping to find other people's analysis report, unfortunately, looked for a long time did not find, more or how to develop Wireshark protocol identification and analysis of plug-ins, very few people analyze its source code. So, I looked for a tool to view the source code more convenient--sourceinsight, to look at these code files, perhaps lucky, look at the look on how it works.

People who have seen Wireshark source code should know that it has a lot of code files, and I am also the first to read so many other people's code, so to integrate the Wireshark protocol analysis code into my project, it is really not easy for me. Spent a lot of time, searched a lot of information, also read a lot of information, finally decided to start from Wireshark command line mode--tshark, analysis Tshark How to identify the network protocol.

I decided to use breakpoint debugging to see how Tshark works, but to debug, you need to compile the connection Wireshark source code. Then began to find information to explore how to compile my Wireshark code. This part of the information is relatively easy to find, but the data are not successfully compiled, and finally on the basis of others, coupled with their own thinking, finally compiled successfully. The previous article describes how to compile Wireshark source code on visual studio2008.

Long winded so much, really began to analyze the Tshark code.

First of all, the successful compilation of the Wireshark source code folder appears a lot of target files, but also generated a wireshark-gtk2 folder, there are several EXE files, such as Wireshark.exe,tshark.exe,dumpcap.exe and so on. The following are the specific examples:




This image is part of the Wireshark-gtk2 folder.

Next, you can use visualstudio2008 (the tool is not limited, but finally with the tool you selected at compile time) to open the WIRESHARK-GTK2 in the directory of the project files, such a number of engineering documents, open one, the others will be automatically added, Because all of the project files are in one solution, as shown in the following figure:



Because only the tshark part of the code, so you can remove it all the project, and then in the Tshark project source file has a tshark.c file, found in the main () function, this is the entry of the program, then you can next breakpoint tracking debugging.

Write this today and attach a detailed analysis report tomorrow.


Wireshark Source Code Analysis Report II

First, the source code structure

Under the Wireshark source code root directory, you can see the following subdirectories:

1) Physical Structure


Among them, the Epan folder is responsible for all network protocol recognition work, plugins inside the Wireshark all plug-ins, gtk folder is Wireshark interface part of the code, the rest of the folder is not alone.

2) Logical Structure

The following figure shows the Ethereal function module: a) gtk1/2

Process user input and output, source code in GTK directory b) Core

Connect other modules together, source code in root directory c) Epan

Ethereal Packetage analyzing, packet analysis engine, source code in Epan directory

L Protocol-tree: Save protocol information for a packet

L Dissectors: Under the Epan/dissector directory, various protocol decoders

L Plugins: Some protocol decoder is implemented in plug-in form, source code in Plugins directory

L Display-filters: Display filter engine, source code in Epan/dfilter directory D) Capture

Packet-catching engine

e) Wiretap

Read the packet from the file, support a variety of file formats, source code in the wiretap directory



Second, Tshark protocol parsing module

The main processing flow is as follows:

The first step:

cf_status_t Cf_open (capture_file *cf, const char *fname, Gboolean is_tempfile, int *err):

The function first calls wtap* wtap_open_offline (const char *filename, int *err, char **err_info,gboolean do_random) function to obtain a WTAP struct.

The definition of WTAP structure is wtap-int.h under the wiretap directory

struct WTAP {
file_t FH;
file_t RANDOM_FH; /* Secondary file_t for random access */
int file_type;
Guint snapshot_length;
struct Buffer *frame_buffer;
struct WTAP_PKTHDR phdr;
Union Wtap_pseudo_header Pseudo_header;

Gint64 Data_offset;
void *priv;

Subtype_read_func Subtype_read;
Subtype_seek_read_func Subtype_seek_read;
void (*subtype_sequential_close) (struct wtap*);
void (*subtype_close) (struct wtap*);
int file_encap; /* Per-file, for those file formats that has per-file encapsulation types */
int tsprecision; /* Timestamp precision of the lower 32bits * e.g. wtap_file_tsprec_usec * *

    wtap_new_ipv4_callback_t Add_new_ipv4;
    wtap_new_ipv6_callback_t Add_new_ipv6;
    gptrarray *fast_seek;
};

A)  wtap_open_offline ()   function process: Call Int libpcap_open (Wtap *wth, int *err,  gchar **err_info) function reads the file header information for a given Pcap file, a total of 28 bytes, as follows:

  File header structure
 sturct pcap_file_header
 {
      dword            magic;//4 bytes
       word           version_major;//major version number, typically 2
      WORD            version_minor;//version number, typically 4
      DWORD            thiszone;
      DWORD            sigfigs;
      DWORD            snaplen;
      DWORD            linktype;
 } 

The Libpcap_open () function reads the Magic information first, and if the file is not modified, continues to read the file header for subsequent information. After reading the entire file header information, determine whether the information is legitimate, if legitimate, and then try to read the first 2 packets of the given Pcap file header record, this work by calling the static libpcap_try_t Libpcap_try (Wtap *wth, int *err) function is complete.

The Libpcap_try () function first calls the Libpcap_read_header () function to read the packet header of the first packet, which is structured as follows:

struct PCAP_PKTHDR
{
struct Tim TS;
DWORD caplen;//captures the actual length of the packet in the Pcap file, in bytes.
The true length of the packet captured by the DWORD len;//.
}

struct Tim
{
The DWORD gmttime;//captures the time of the packet, from 00:00:00 GMT, January 1, 1970, to the number of seconds after the packet was caught.
DWORD microtime;//the Microsecond value when fetching packets.
}

The packet header is 16 bytes in total. Then call File_seek () (the function's primary function is to implement file positioning) after the function navigates to the first packet, that is, the length of the data portion of the first packet of the 24-byte header + 16 bytes of data header +caplen bytes. If the File_seek () operation is correct, that is, no-1 is returned, the Libpcap_try () function calls the Libpcap_read_header () function again to read the header information of the second packet. If the read is correct, the Libpcap_try () function returns This_format, indicating that the Pcap file is properly formatted.

At this point Libpcap_open () calls File_seek () to the file header of the given Pcap file, which is 24 bytes, and returns 1, indicating that the operation was successful.

b) the Wtap_open_offline () function allocates a maximum space of 1500 bytes for the buffer portion of the Wtap frame_buffer struct, and then returns the WTAP information for the given Pcap file.

c) when the Wtap_open_offline () function correctly returns the WTAP information, the Cf_open () function calls the Cleanup_dissection () function to empty the data structure that will be used in the protocol parsing work. Cleanup_dissection () 's emptying work includes:

1) Conversation (Epan_conversation_cleanup ());

2) Circuits (Epan_circuit_cleanup ());

3) protocol-specific variables (G_slist_foreach (Init_routines, &call_init_routine, NULL));

4) stream-handling tables (Stream_cleanup ());

5) Expert Infos (Expert_cleanup ()). After Cleanup_dissection () returns, the Cf_open () function calls the Init_dissection () function to initialize all data to be used in subsequent parsing work. The initialization of init_dissection () is basically consistent with the contents of cleanup_dissection () emptying. After the work is done, set the Capture_file information and return to the main () function.

2. Set the time accuracy

3. static int Load_cap_file (Capture_file *cf, char *save_file, int out_file_type, Gboolean out_file_name_res, int max_pack The Et_count, Gint64 max_byte_count) function loads the given pcap file.

The specific work done by the Load_cap_file () function is as follows:

A) if the Save_file (save captured packet information) parameter is not empty, call the Wtap_dump_open () function to get the wtap_dump struct.

b) Call Gboolean Wtap_read (wtap *wth, int *err, Gchar **err_info, Gint64 *data_offset) function to read the given Pcap file data.

c) Call the function subtype_read in the WTAP structure, the Libpcap_read () function, to read the next packet data. This part of the process is similar to the processing in the first stage of Cf_open (), which means that the Libpcap_read () function calls the Libpcap_read_header () function to read the header portion of the next packet 16 bytes, The specific reading of the 16-byte header is done by the Libpcap_read_header () function call File_read ().

D) if the Libpcap_read_header () operation is correct and the number of bytes of packet read is successfully returned, the Libpcap_read () function adjusts the file pointer offset and then calls Pcap_process_pseudo_header () The function processes the Pseudo_header information of the packet, primarily to determine the length of the FCS. (Pseudo translated into "fake, fake", may be some packets of some fake Baotou bar, not very understanding. ) and return the length of the Pseudo_header.

e) the Libpcap_reader () function adjusts the actual length of the packet and the offset of the file based on the returned pseudo_header length, as follows:

Orig_size = Phdr_len;//phdr_len is the length of pseudo_header.

Packet_size-= Phdr_len;

Wth->data_offset + = Phdr_len;

f) the Libpcap_read () function calls the Buffer_assure_space () function to ensure that the allocated space in the Frame_buffer in the WTAP structure is sufficient to accommodate the size of the packet being read, and if not enough, the frame_ The contents of the space already used in buffer are moved to the front of the Frame_buffer, then 1024 bytes are allocated to Frame_buffer and returned.

g) the Libpcap_read () function calls the Libpcap_read_rec_data () function to read the data portion of the changed packet, and the specific read work is also done by the File_read () function.

h) Adjust the file offset, update timestamp, call the Pcap_read_post_process () function, and according to the WTAP_ENCAP value, determine the Eth.fcs_len size of the pseudo_header.

i) Libpcap_read () work is completed and returned to Wtap_read (), if Libpcap_read () returns True,wtap_read () also returns True.

j) Call Static Gboolean Process_packet (capture_file *cf, gint64 offset, const struct WTAP_PKTHDR *WHDR, Union Wtap_pseudo_hea Der *pseudo_header, const Guchar *PD, Gboolean filtering_tap_listeners, Guint tap_flags) functions handle the contents of the packet read before. Here's how:

The Process_packet () function calls the Frame_data_init () function to initialize the frame data structure of the packet, including the data header information. If you need to parse the packet, determine if you need to create a protocol tree (print Protocol details), then call epan_dissect_t* epan_dissect_init (epan_dissect_t *edt, const Gboolean Create_ The Proto_tree, const Gboolean proto_tree_visible) function completes the initialization work before parsing. In the Epan_dissect_init () function, if Create_proto_tree is true, call the Protp_tree_create_root () function to create the root node of the protocol tree and assign a value of Edt->tree, and Call Proto_tree_set_visible () to set the visibility of the protocol tree to the value of the proto_tree_visible parameter. If Create_proto_tree is False, edt->tree=null; returns EDT. At this point, the work of Epan_dissect_init () was completed

II. Next, determine if a read filter is set, that is, whether the rfnode of the capture_file struct is empty. If it is not empty, call Epan_dissect_prime_dfilter (&edt, Cf->rfnode) for processing (the specific process has not been tracked for debugging.) )。

III. Call void Col_custom_prime_edt (epan_dissect_t *edt, Column_info *cinfo) function (this function is not specific to the task). If there is no user-defined print content, it is returned directly, otherwise, according to user settings, do something.

Iv. Call the void Tap_queue_init (epan_dissect_t *edt) function to initialize the tap queue.

V. Call the Frame_data_set_before_dissect () function to set the action before parsing the frame data.

Specific content includes:

1) Set the timestamp of the first package and the previous package. If First_ts is not set, the current packet is the first packet, then the FIRST_TS is set to the time of the first packet, and if Prev_cap_ts is not set, it also indicates that the current packet is the first packet, then it is also set to the time of the first package, that is, frame_ The Abs_ts property of the data structure body.

2) Calculate the difference between the current packet receive time and the first packet receive time.

3) Calculate the difference between the received time of the packet that the previous packet has been printed and the current packet's receive time. If the received time of the previous printed packet is not set, then no packet has been printed before the current packet. At this time, the previous printed packet is set to the receiving time of 0, otherwise the difference is calculated.

4) Calculate the difference between the capture time of the previous packet and the capture time of the current packet, and save it to the Del_cap_ts attribute of the frame_date.

5) When the above 4 steps are completed, the capture time of the previous packet is set to the capture time of the current packet and returned to Process_packet ().

Vi. calling void Epan_dissect_run (epan_dissect_t *edt, void* pseudo_header, const guint8* data, Frame_data *fd, Column_info *cin FO) function to begin the real parsing work. The process of the function is roughly as follows:

A) call the Ep_free_all () function to release all the memory allocated in the parsing work in the previous packet.

b) call void Dissect_packet (epan_dissect_t *edt, Union wtap_pseudo_header *pseudo_header, const Guchar *PD, Frame_data *fd, C Olumn_info *cinfo) function for parsing.

The specific actions are:

1) if

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.