language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
C/C++
wireshark/wsutil/filesystem.h
/** @file * Filesystem utility definitions * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef FILESYSTEM_H #define FILESYSTEM_H #include <wireshark.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Default profile name. */ #define DEFAULT_PROFILE "Default" /** * Initialize our configuration environment. * * Get the pathname of the directory from which the executable came, * and save it for future use. * * Set our configuration namespace, which determines the top-level * configuration directory name and environment variable prefixes. * Default is "Wireshark". * * @param arg0 Executable name hint. Should be argv[0]. * @param namespace_name The namespace to use. "Wireshark" or NULL uses * the Wireshark namespace. "Logray" uses the Logray namespace. * @return NULL on success, and a g_mallocated string containing an error on failure. */ WS_DLL_PUBLIC char *configuration_init(const char *arg0, const char *namespace_name); /** * Get the configuration namespace name. * @return The namespace name. One of "Wireshark" or "Logray". */ WS_DLL_PUBLIC const char *get_configuration_namespace(void); /** * Check to see if the configuration namespace is for packet analysis * (Wireshark) or log analysis (Logray). * @return true if the configuration namespace is for packets. */ WS_DLL_PUBLIC bool is_packet_configuration_namespace(void); /* * Get the directory in which the main (Wireshark, TShark, Logray, etc) * program resides. * Extcaps should use get_extcap_dir() to get their path. * * @return The main program file directory. */ WS_DLL_PUBLIC const char *get_progfile_dir(void); /* * Construct the path name of a non-extcap Wireshark executable file, * given the program name. The executable name doesn't include ".exe"; * append it on Windows, so that callers don't have to worry about that. * * This presumes that all non-extcap executables are in the same directory. * * The returned file name was g_malloc()'d so it must be g_free()d when the * caller is done with it. */ WS_DLL_PUBLIC char *get_executable_path(const char *filename); /* * Get the directory in which plugins are stored; this must not be called * before configuration_init() is called, as they might be stored in a * subdirectory of the program file directory. */ WS_DLL_PUBLIC const char *get_plugins_dir(void); /* * Append VERSION_MAJOR.VERSION_MINOR to the plugin dir. */ WS_DLL_PUBLIC const char *get_plugins_dir_with_version(void); /* * Get the personal plugin dir. */ WS_DLL_PUBLIC const char *get_plugins_pers_dir(void); /* * Append VERSION_MAJOR.VERSION_MINOR to the plugin personal dir. */ WS_DLL_PUBLIC const char *get_plugins_pers_dir_with_version(void); /* * Get the directory in which extcap hooks are stored; this must not be called * before configuration_init() is called, as they might be stored in a * subdirectory of the program file directory. */ WS_DLL_PUBLIC const char *get_extcap_dir(void); /* * Get the personal extcap dir. */ WS_DLL_PUBLIC const char *get_extcap_pers_dir(void); /* * Get the flag indicating whether we're running from a build * directory. */ WS_DLL_PUBLIC gboolean running_in_build_directory(void); /* * Get the directory in which global configuration files are * stored. */ WS_DLL_PUBLIC const char *get_datafile_dir(void); /* * Construct the path name of a global configuration file, given the * file name. * * The returned file name was g_malloc()'d so it must be g_free()d when the * caller is done with it. */ WS_DLL_PUBLIC char *get_datafile_path(const char *filename); /* * Get the directory in which global documentation files are * stored. */ WS_DLL_PUBLIC const char *get_doc_dir(void); /* * Construct the path name of a global documentation file, given the * file name. * * The returned file name was g_malloc()'d so it must be g_free()d when the * caller is done with it. */ WS_DLL_PUBLIC char *get_docfile_path(const char *filename); /* * Construct the path URL of a global documentation file, given the * file name. * * The returned file name was g_malloc()'d so it must be g_free()d when the * caller is done with it. */ WS_DLL_PUBLIC char *doc_file_url(const char *filename); /* * Get the directory in which files that, at least on UNIX, are * system files (such as "/etc/ethers") are stored; on Windows, * there's no "/etc" directory, so we get them from the Wireshark * global configuration and data file directory. */ WS_DLL_PUBLIC const char *get_systemfile_dir(void); /* * Set the configuration profile name to be used for storing * personal configuration files. */ WS_DLL_PUBLIC void set_profile_name(const gchar *profilename); /* * Get the current configuration profile name used for storing * personal configuration files. */ WS_DLL_PUBLIC const char *get_profile_name(void); /* * Check if current profile is default profile. */ WS_DLL_PUBLIC gboolean is_default_profile(void); /* * Check if we have global profiles. */ WS_DLL_PUBLIC gboolean has_global_profiles(void); /* * Get the directory used to store configuration profile directories. * Caller must free the returned string */ WS_DLL_PUBLIC char *get_profiles_dir(void); /* * Get the directory used to store configuration files for a given profile. * Caller must free the returned string. */ WS_DLL_PUBLIC char *get_profile_dir(const char *profilename, gboolean is_global); /* * Create the directory used to store configuration profile directories. */ WS_DLL_PUBLIC int create_profiles_dir(char **pf_dir_path_return); /* * Get the directory used to store global configuration profile directories. * Caller must free the returned string */ WS_DLL_PUBLIC char *get_global_profiles_dir(void); /* * Store filenames used for personal config files so we know which * files to copy when duplicate a configuration profile. */ WS_DLL_PUBLIC void profile_store_persconffiles(gboolean store); /* * Register a filename to the personal config files storage. * This is for files which are not read using get_persconffile_path() during startup. */ WS_DLL_PUBLIC void profile_register_persconffile(const char *filename); /* * Check if given configuration profile exists. */ WS_DLL_PUBLIC gboolean profile_exists(const gchar *profilename, gboolean global); /* * Create a directory for the given configuration profile. * If we attempted to create it, and failed, return -1 and * set "*pf_dir_path_return" to the pathname of the directory we failed * to create (it's g_mallocated, so our caller should free it); otherwise, * return 0. */ WS_DLL_PUBLIC int create_persconffile_profile(const char *profilename, char **pf_dir_path_return); /* * Returns the list of known profile config filenames */ WS_DLL_PUBLIC const GHashTable * allowed_profile_filenames(void); /* * Delete the directory for the given configuration profile. * If we attempted to delete it, and failed, return -1 and * set "*pf_dir_path_return" to the pathname of the directory we failed * to delete (it's g_mallocated, so our caller should free it); otherwise, * return 0. */ WS_DLL_PUBLIC int delete_persconffile_profile(const char *profilename, char **pf_dir_path_return); /* * Rename the directory for the given confinguration profile. */ WS_DLL_PUBLIC int rename_persconffile_profile(const char *fromname, const char *toname, char **pf_from_dir_path_return, char **pf_to_dir_path_return); /* * Copy files in one profile to the other. */ WS_DLL_PUBLIC int copy_persconffile_profile(const char *toname, const char *fromname, gboolean from_global, char **pf_filename_return, char **pf_to_dir_path_return, char **pf_from_dir_path_return); /* * Create the directory that holds personal configuration files, if * necessary. If we attempted to create it, and failed, return -1 and * set "*pf_dir_path_return" to the pathname of the directory we failed * to create (it's g_mallocated, so our caller should free it); otherwise, * return 0. */ WS_DLL_PUBLIC int create_persconffile_dir(char **pf_dir_path_return); /* * Construct the path name of a personal configuration file, given the * file name. If using configuration profiles this directory will be * used if "from_profile" is TRUE. * * The returned file name was g_malloc()'d so it must be g_free()d when the * caller is done with it. */ WS_DLL_PUBLIC char *get_persconffile_path(const char *filename, gboolean from_profile); /* * Set the path of the personal configuration file directory. */ WS_DLL_PUBLIC void set_persconffile_dir(const char *p); /* * Get the (default) directory in which personal data is stored. * * On Win32, this is the "My Documents" folder in the personal profile. * On UNIX this is simply the current directory. */ WS_DLL_PUBLIC const char *get_persdatafile_dir(void); /* * Set the path of the directory in which personal data is stored. */ WS_DLL_PUBLIC void set_persdatafile_dir(const char *p); /* * Return an error message for UNIX-style errno indications on open or * create operations. */ WS_DLL_PUBLIC const char *file_open_error_message(int err, gboolean for_writing); /* * Return an error message for UNIX-style errno indications on write * operations. */ WS_DLL_PUBLIC const char *file_write_error_message(int err); /* * Given a pathname, return the last component. */ WS_DLL_PUBLIC const char *get_basename(const char *); /* * Given a pathname, return a pointer to the last pathname separator * character in the pathname, or NULL if the pathname contains no * separators. */ WS_DLL_PUBLIC char *find_last_pathname_separator(const char *path); /* * Given a pathname, return a string containing everything but the * last component. NOTE: this overwrites the pathname handed into * it.... */ WS_DLL_PUBLIC char *get_dirname(char *); /* * Given a pathname, return: * * the errno, if an attempt to "stat()" the file fails; * * EISDIR, if the attempt succeeded and the file turned out * to be a directory; * * 0, if the attempt succeeded and the file turned out not * to be a directory. */ WS_DLL_PUBLIC int test_for_directory(const char *); /* * Given a pathname, return: * * the errno, if an attempt to "stat()" the file fails; * * ESPIPE, if the attempt succeeded and the file turned out * to be a FIFO; * * 0, if the attempt succeeded and the file turned out not * to be a FIFO. */ WS_DLL_PUBLIC int test_for_fifo(const char *); /* * Check, if file is existing. */ WS_DLL_PUBLIC gboolean file_exists(const char *fname); /* * Check if file is existing and has text entries which does not start * with the comment character. */ WS_DLL_PUBLIC gboolean config_file_exists_with_entries(const char *fname, char comment_char); /* * Check if two filenames are identical (with absolute and relative paths). */ WS_DLL_PUBLIC gboolean files_identical(const char *fname1, const char *fname2); /* * Check if file has been recreated since it was opened. */ WS_DLL_PUBLIC gboolean file_needs_reopen(int fd, const char* filename); /* * Write content to a file in binary mode, for those operating systems that * care about such things. This should be OK for all files, even text files, as * we'll write the raw bytes, and we don't look at the bytes as we copy them. * * Returns TRUE on success, FALSE on failure. If a failure, it also * displays a simple dialog window with the error message. */ WS_DLL_PUBLIC gboolean write_file_binary_mode(const char *filename, const void *content, size_t content_len); /* * Copy a file in binary mode, for those operating systems that care about * such things. This should be OK for all files, even text files, as * we'll copy the raw bytes, and we don't look at the bytes as we copy * them. * * Returns TRUE on success, FALSE on failure. If a failure, it also * displays a simple dialog window with the error message. */ WS_DLL_PUBLIC gboolean copy_file_binary_mode(const char *from_filename, const char *to_filename); /* * Given a filename return a filesystem URL. Relative paths are prefixed with * the datafile directory path. * * @param filename A file name or path. Relative paths will be prefixed with * the data file directory path. * @return A filesystem URL for the file or NULL on failure. A non-NULL return * value must be freed with g_free(). */ WS_DLL_PUBLIC gchar* data_file_url(const gchar *filename); /* * Free the internal structtures */ WS_DLL_PUBLIC void free_progdirs(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* FILESYSTEM_H */
C
wireshark/wsutil/file_util.c
/* file_util.c * * (Originally part of the Wiretap Library, now part of the Wireshark * utility library) * Copyright (c) 1998 by Gilbert Ramirez <[email protected]> * * SPDX-License-Identifier: GPL-2.0-or-later */ /* * File wrapper functions to replace the file functions from GLib like * g_open(). * * With MSVC, code using the C support library from one version of MSVC * cannot use file descriptors or FILE *'s returned from code using * the C support library from another version of MSVC. * * We therefore provide our own versions of the routines to open files, * so that they're built to use the same C support library as our code * that reads them. * * (If both were built to use the Universal CRT: * * http://blogs.msdn.com/b/vcblog/archive/2015/03/03/introducing-the-universal-crt.aspx * * this would not be a problem.) * * DO NOT USE THESE FUNCTIONS DIRECTLY, USE ws_open() AND ALIKE FUNCTIONS * FROM file_util.h INSTEAD!!! * * The following code is stripped down code copied from the GLib file * glib/gstdio.h - stripped down because this is used only on Windows * and we use only wide char functions. * * In addition, we have our own ws_stdio_stat64(), which uses * _wstati64(), so that we can get file sizes for files > 4 GB in size. * * XXX - is there any reason why we supply our own versions of routines * that *don't* return file descriptors, other than ws_stdio_stat64()? * Is there an issue with UTF-16 support in _wmkdir() with some versions * of the C runtime, so that if GLib is built to use that version, it * won't handle UTF-16 paths? */ #ifndef _WIN32 #error "This is only for Windows" #endif #include "config.h" #include <glib.h> #include <windows.h> #include <winsock2.h> #include <errno.h> #include <wchar.h> #include <tchar.h> #include <stdlib.h> #include "file_util.h" #include "ws_attributes.h" static gchar *program_path = NULL; static gchar *system_path = NULL; static gchar *npcap_path = NULL; /** * g_open: * @filename: a pathname in the GLib file name encoding (UTF-8 on Windows) * @flags: as in open() * @mode: as in open() * * A wrapper for the POSIX open() function. The open() function is * used to convert a pathname into a file descriptor. Note that on * POSIX systems file descriptors are implemented by the operating * system. On Windows, it's the C library that implements open() and * file descriptors. The actual Windows API for opening files is * something different. * * See the C library manual for more details about open(). * * Returns: a new file descriptor, or -1 if an error occurred. The * return value can be used exactly like the return value from open(). * * Since: 2.6 */ int ws_stdio_open (const gchar *filename, int flags, int mode) { wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL); int retval; int save_errno; if (wfilename == NULL) { errno = EINVAL; return -1; } retval = _wopen (wfilename, flags, mode); save_errno = errno; g_free (wfilename); errno = save_errno; return retval; } /** * g_rename: * @oldfilename: a pathname in the GLib file name encoding (UTF-8 on Windows) * @newfilename: a pathname in the GLib file name encoding * * A wrapper for the POSIX rename() function. The rename() function * renames a file, moving it between directories if required. * * See your C library manual for more details about how rename() works * on your system. Note in particular that on Win9x it is not possible * to rename a file if a file with the new name already exists. Also * it is not possible in general on Windows to rename an open file. * * Returns: 0 if the renaming succeeded, -1 if an error occurred * * Since: 2.6 */ int ws_stdio_rename (const gchar *oldfilename, const gchar *newfilename) { wchar_t *woldfilename = g_utf8_to_utf16 (oldfilename, -1, NULL, NULL, NULL); wchar_t *wnewfilename; int retval; int save_errno = 0; if (woldfilename == NULL) { errno = EINVAL; return -1; } wnewfilename = g_utf8_to_utf16 (newfilename, -1, NULL, NULL, NULL); if (wnewfilename == NULL) { g_free (woldfilename); errno = EINVAL; return -1; } if (MoveFileExW (woldfilename, wnewfilename, MOVEFILE_REPLACE_EXISTING)) retval = 0; else { retval = -1; switch (GetLastError ()) { #define CASE(a,b) case ERROR_##a: save_errno = b; break CASE (FILE_NOT_FOUND, ENOENT); CASE (PATH_NOT_FOUND, ENOENT); CASE (ACCESS_DENIED, EACCES); CASE (NOT_SAME_DEVICE, EXDEV); CASE (LOCK_VIOLATION, EACCES); CASE (SHARING_VIOLATION, EACCES); CASE (FILE_EXISTS, EEXIST); CASE (ALREADY_EXISTS, EEXIST); #undef CASE default: save_errno = EIO; } } g_free (woldfilename); g_free (wnewfilename); errno = save_errno; return retval; } /** * g_mkdir: * @filename: a pathname in the GLib file name encoding (UTF-8 on Windows) * @mode: permissions to use for the newly created directory * * A wrapper for the POSIX mkdir() function. The mkdir() function * attempts to create a directory with the given name and permissions. * * See the C library manual for more details about mkdir(). * * Returns: 0 if the directory was successfully created, -1 if an error * occurred * * Since: 2.6 */ int ws_stdio_mkdir (const gchar *filename, int mode _U_) { wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL); int retval; int save_errno; if (wfilename == NULL) { errno = EINVAL; return -1; } retval = _wmkdir (wfilename); save_errno = errno; g_free (wfilename); errno = save_errno; return retval; } /** * g_stat: * @filename: a pathname in the GLib file name encoding (UTF-8 on Windows) * @buf: a pointer to a <structname>stat</structname> struct, which * will be filled with the file information * * A wrapper for the POSIX stat() function. The stat() function * returns information about a file. * * See the C library manual for more details about stat(). * * Returns: 0 if the information was successfully retrieved, -1 if an error * occurred * * Since: 2.6 */ int ws_stdio_stat64 (const gchar *filename, ws_statb64 *buf) { wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL); int retval; int save_errno; size_t len; if (wfilename == NULL) { errno = EINVAL; return -1; } len = wcslen (wfilename); while (len > 0 && G_IS_DIR_SEPARATOR (wfilename[len-1])) len--; if (len > 0 && (!g_path_is_absolute (filename) || len > (size_t) (g_path_skip_root (filename) - filename))) wfilename[len] = '\0'; retval = _wstati64 (wfilename, buf); save_errno = errno; g_free (wfilename); errno = save_errno; return retval; } /** * g_unlink: * @filename: a pathname in the GLib file name encoding (UTF-8 on Windows) * * A wrapper for the POSIX unlink() function. The unlink() function * deletes a name from the filesystem. If this was the last link to the * file and no processes have it opened, the diskspace occupied by the * file is freed. * * See your C library manual for more details about unlink(). Note * that on Windows, it is in general not possible to delete files that * are open to some process, or mapped into memory. * * Returns: 0 if the name was successfully deleted, -1 if an error * occurred * * Since: 2.6 */ int ws_stdio_unlink (const gchar *filename) { wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL); int retval; int save_errno; if (wfilename == NULL) { errno = EINVAL; return -1; } retval = _wunlink (wfilename); save_errno = errno; g_free (wfilename); errno = save_errno; return retval; } /** * g_remove: * @filename: a pathname in the GLib file name encoding (UTF-8 on Windows) * * A wrapper for the POSIX remove() function. The remove() function * deletes a name from the filesystem. * * See your C library manual for more details about how remove() works * on your system. On Unix, remove() removes also directories, as it * calls unlink() for files and rmdir() for directories. On Windows, * although remove() in the C library only works for files, this * function tries first remove() and then if that fails rmdir(), and * thus works for both files and directories. Note however, that on * Windows, it is in general not possible to remove a file that is * open to some process, or mapped into memory. * * If this function fails on Windows you can't infer too much from the * errno value. rmdir() is tried regardless of what caused remove() to * fail. Any errno value set by remove() will be overwritten by that * set by rmdir(). * * Returns: 0 if the file was successfully removed, -1 if an error * occurred * * Since: 2.6 */ int ws_stdio_remove (const gchar *filename) { wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL); int retval; int save_errno; if (wfilename == NULL) { errno = EINVAL; return -1; } retval = _wremove (wfilename); if (retval == -1) retval = _wrmdir (wfilename); save_errno = errno; g_free (wfilename); errno = save_errno; return retval; } /** * g_fopen: * @filename: a pathname in the GLib file name encoding (UTF-8 on Windows) * @mode: a string describing the mode in which the file should be * opened * * A wrapper for the POSIX fopen() function. The fopen() function opens * a file and associates a new stream with it. * * See the C library manual for more details about fopen(). * * Returns: A <type>FILE</type> pointer if the file was successfully * opened, or %NULL if an error occurred * * Since: 2.6 */ FILE * ws_stdio_fopen (const gchar *filename, const gchar *mode) { wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL); wchar_t *wmode; FILE *retval; int save_errno; if (wfilename == NULL) { errno = EINVAL; return NULL; } wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL); if (wmode == NULL) { g_free (wfilename); errno = EINVAL; return NULL; } retval = _wfopen (wfilename, wmode); save_errno = errno; g_free (wfilename); g_free (wmode); errno = save_errno; return retval; } /** * g_freopen: * @filename: a pathname in the GLib file name encoding (UTF-8 on Windows) * @mode: a string describing the mode in which the file should be * opened * @stream: an existing stream which will be reused, or %NULL * * A wrapper for the POSIX freopen() function. The freopen() function * opens a file and associates it with an existing stream. * * See the C library manual for more details about freopen(). * * Returns: A <type>FILE</type> pointer if the file was successfully * opened, or %NULL if an error occurred. * * Since: 2.6 */ FILE * ws_stdio_freopen (const gchar *filename, const gchar *mode, FILE *stream) { wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL); wchar_t *wmode; FILE *retval; int save_errno; if (wfilename == NULL) { errno = EINVAL; return NULL; } wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL); if (wmode == NULL) { g_free (wfilename); errno = EINVAL; return NULL; } retval = _wfreopen (wfilename, wmode, stream); save_errno = errno; g_free (wfilename); g_free (wmode); errno = save_errno; return retval; } /* DLL loading */ static gboolean init_dll_load_paths(void) { TCHAR path_w[MAX_PATH]; if (program_path && system_path && npcap_path) return TRUE; /* XXX - Duplicate code in filesystem.c:configuration_init */ if (GetModuleFileName(NULL, path_w, MAX_PATH) == 0 || GetLastError() == ERROR_INSUFFICIENT_BUFFER) { return FALSE; } if (!program_path) { gchar *app_path; app_path = g_utf16_to_utf8(path_w, -1, NULL, NULL, NULL); /* We could use PathRemoveFileSpec here but we'd have to link to Shlwapi.dll */ program_path = g_path_get_dirname(app_path); g_free(app_path); } if (GetSystemDirectory(path_w, MAX_PATH) == 0) { return FALSE; } if (!system_path) { system_path = g_utf16_to_utf8(path_w, -1, NULL, NULL, NULL); } _tcscat_s(path_w, MAX_PATH, _T("\\Npcap")); if (!npcap_path) { npcap_path = g_utf16_to_utf8(path_w, -1, NULL, NULL, NULL); } if (program_path && system_path && npcap_path) return TRUE; return FALSE; } gboolean ws_init_dll_search_path(void) { gboolean dll_dir_set = FALSE; wchar_t *program_path_w; /* Remove the current directory from the default DLL search path. */ SetDllDirectory(_T("")); if (init_dll_load_paths()) { /* Ensure that extcap executables can find wsutil, etc. */ program_path_w = g_utf8_to_utf16(program_path, -1, NULL, NULL, NULL); dll_dir_set = SetDllDirectory(program_path_w); g_free(program_path_w); } return dll_dir_set; } /* * Internally g_module_open uses LoadLibrary on Windows and returns an * HMODULE cast to a GModule *. However there's no guarantee that this * will always be the case, so we call LoadLibrary and g_module_open * separately. */ void * ws_load_library(const gchar *library_name) { gchar *full_path; wchar_t *full_path_w; HMODULE dll_h; if (!init_dll_load_paths() || !library_name) return NULL; /* First try the program directory */ full_path = g_strconcat(program_path, G_DIR_SEPARATOR_S, library_name, NULL); full_path_w = g_utf8_to_utf16(full_path, -1, NULL, NULL, NULL); if (full_path && full_path_w) { dll_h = LoadLibraryW(full_path_w); if (dll_h) { g_free(full_path); g_free(full_path_w); return dll_h; } } /* Next try the system directory */ full_path = g_strconcat(system_path, G_DIR_SEPARATOR_S, library_name, NULL); full_path_w = g_utf8_to_utf16(full_path, -1, NULL, NULL, NULL); if (full_path && full_path_w) { dll_h = LoadLibraryW(full_path_w); if (dll_h) { g_free(full_path); g_free(full_path_w); return dll_h; } } return NULL; } static GModule * load_npcap_module(const gchar *full_path, GModuleFlags flags) { /* * Npcap's wpcap.dll requires packet.dll from the same directory. Either * SetDllDirectory or SetCurrentDirectory could make this work, but it * interferes with other uses of these settings. LoadLibraryEx is ideal as * it can be configured to put the directory containing the DLL to the * search path. Unfortunately g_module_open uses LoadLibrary internally, so * as a workaround manually load the Npcap libraries first and then use * g_module_open to obtain a GModule for the loaded library. */ wchar_t *wpath = g_utf8_to_utf16(full_path, -1, NULL, NULL, NULL); HMODULE module = LoadLibraryEx(wpath, NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR); g_free(wpath); if (!module) { return NULL; } GModule *mod = g_module_open(full_path, flags); FreeLibrary(module); return mod; } GModule * load_wpcap_module(void) { gchar *module_name = "wpcap.dll"; gchar *full_path; GModule *mod; GModuleFlags flags = 0; if (!init_dll_load_paths()) return NULL; /* First try the program directory */ full_path = g_strconcat(program_path, G_DIR_SEPARATOR_S, module_name, NULL); if (full_path) { mod = g_module_open(full_path, flags); g_free(full_path); if (mod) { return mod; } } /* Next try the Npcap directory */ full_path = g_strconcat(npcap_path, G_DIR_SEPARATOR_S, module_name, NULL); if (full_path) { mod = load_npcap_module(full_path, flags); g_free(full_path); if (mod) { return mod; } } /* At last try the system directory */ full_path = g_strconcat(system_path, G_DIR_SEPARATOR_S, module_name, NULL); if (full_path) { mod = g_module_open(full_path, flags); g_free(full_path); if (mod) { return mod; } } return NULL; } /** Create or open a "Wireshark is running" mutex. */ #define WIRESHARK_IS_RUNNING_UUID "9CA78EEA-EA4D-4490-9240-FC01FCEF464B" static HANDLE local_running_mutex = NULL; static HANDLE global_running_mutex = NULL; void create_app_running_mutex(void) { SECURITY_DESCRIPTOR sec_descriptor; SECURITY_ATTRIBUTES sec_attributes; SECURITY_ATTRIBUTES *sa; memset(&sec_descriptor, 0, sizeof(SECURITY_DESCRIPTOR)); if (!InitializeSecurityDescriptor(&sec_descriptor, SECURITY_DESCRIPTOR_REVISION) || !SetSecurityDescriptorDacl(&sec_descriptor, TRUE, NULL, FALSE)) { /* * We couldn't set up the security descriptor, so use the default * security attributes when creating the mutexes. */ sa = NULL; } else { /* * We could set it up, so set up some attributes that refer * to it. */ memset(&sec_attributes, 0, sizeof(SECURITY_ATTRIBUTES)); sec_attributes.nLength = sizeof(SECURITY_ATTRIBUTES); sec_attributes.lpSecurityDescriptor = &sec_descriptor; sec_attributes.bInheritHandle = TRUE; sa = &sec_attributes; } local_running_mutex = CreateMutex(sa, FALSE, _T("Wireshark-is-running-{") _T(WIRESHARK_IS_RUNNING_UUID) _T("}")); global_running_mutex = CreateMutex(sa, FALSE, _T("Global\\Wireshark-is-running-{") _T(WIRESHARK_IS_RUNNING_UUID) _T("}")); } void close_app_running_mutex(void) { if (local_running_mutex) { CloseHandle(local_running_mutex); local_running_mutex = NULL; } if (global_running_mutex) { CloseHandle(global_running_mutex); global_running_mutex = NULL; } } int ws_close_if_possible(int fd) { fd_set rfds; struct timeval tv = { 0, 1 }; int retval; FD_ZERO(&rfds); FD_SET(fd, &rfds); retval = select(1, &rfds, NULL, NULL, &tv); if (retval > -1) return _close(fd); return -1; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * 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: */
C/C++
wireshark/wsutil/file_util.h
/** @file * File utility definitions * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __FILE_UTIL_H__ #define __FILE_UTIL_H__ #include <glib.h> #include "ws_symbol_export.h" #ifdef _WIN32 #include <io.h> /* for _read(), _write(), etc. */ #include <gmodule.h> #endif #include <fcntl.h> /* for open() */ #ifdef HAVE_UNISTD_H #include <unistd.h> /* for read(), write(), close(), etc. */ #endif #include <sys/stat.h> /* for stat() and struct stat */ #include <stdio.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* We set a larger IO Buffer size for the capture files */ #define IO_BUF_SIZE (64 * 1024) /* * Visual C++ on Win32 systems doesn't define these. (Old UNIX systems don't * define them either.) * * Visual C++ on Win32 systems doesn't define S_IFIFO, it defines _S_IFIFO. */ #ifndef S_ISREG #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) #endif #ifndef S_IFIFO #define S_IFIFO _S_IFIFO #endif #ifndef S_ISFIFO #define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) #endif #ifndef S_ISDIR #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) #endif #ifdef _WIN32 /* * The structure to pass to ws_stat64() and ws_fstat64(). */ #define ws_statb64 struct _stat64 /* Win32 (and Win64): we use UTF-8 for filenames and pathnames throughout * the code, so file functions must convert filenames and pathnames from * UTF-8 to UTF-16 as we use NT Unicode (Win9x - now unsupported - used * locale-based encoding here). Microsoft's UN*X-style wrappers don't * do that - they expect locale-based encodings - so we need our own * wrappers. (We don't use the wrappers from GLib as that would, at * least for the wrappers that return file descriptors or take them * as arguments, require that we use the version of the C runtime with * which the GLib binaries were built, and we can't guarantee to do that.) * * Note also that ws_stdio_rename() uses MoveFileEx() with * MOVEFILE_REPLACE_EXISTING, so that it acts like UN*X rename(), * removing the target if necessary. */ WS_DLL_PUBLIC int ws_stdio_open (const gchar *filename, int flags, int mode); WS_DLL_PUBLIC int ws_stdio_rename (const gchar *oldfilename, const gchar *newfilename); WS_DLL_PUBLIC int ws_stdio_mkdir (const gchar *filename, int mode); WS_DLL_PUBLIC int ws_stdio_stat64 (const gchar *filename, ws_statb64 *buf); WS_DLL_PUBLIC int ws_stdio_unlink (const gchar *filename); WS_DLL_PUBLIC int ws_stdio_remove (const gchar *filename); WS_DLL_PUBLIC FILE * ws_stdio_fopen (const gchar *filename, const gchar *mode); WS_DLL_PUBLIC FILE * ws_stdio_freopen (const gchar *filename, const gchar *mode, FILE *stream); #define ws_open ws_stdio_open #define ws_rename ws_stdio_rename #define ws_mkdir ws_stdio_mkdir #define ws_stat64 ws_stdio_stat64 #define ws_unlink ws_stdio_unlink #define ws_remove ws_stdio_remove #define ws_fopen ws_stdio_fopen #define ws_freopen ws_stdio_freopen /* * These routines don't take pathnames, so they don't require * pathname-converting wrappers on Windows. */ typedef unsigned int ws_file_size_t; typedef signed int ws_file_ssize_t; #define ws_read _read #define ws_write _write #define ws_close _close #define ws_dup _dup #define ws_fseek64 _fseeki64 /* use _fseeki64 for 64-bit offset support */ #define ws_fstat64 _fstati64 /* use _fstati64 for 64-bit size support */ #define ws_ftell64 _ftelli64 /* use _ftelli64 for 64-bit offset support */ #define ws_lseek64 _lseeki64 /* use _lseeki64 for 64-bit offset support */ #define ws_fdopen _fdopen #define ws_fileno _fileno #define ws_isatty _isatty #define ws_getc_unlocked _fgetc_nolock /* * Other CRT functions. getpid probably belongs in sys_util.h or proc_util.h * but neither yet exist. */ #define ws_getpid _getpid #define ws_umask _umask /* DLL loading */ /** Try to remove the current directory from the DLL search path. * SetDllDirectory is tried, then SetCurrentDirectory(program_dir) * * @return TRUE if we were able to call SetDllDirectory, FALSE otherwise. */ WS_DLL_PUBLIC gboolean ws_init_dll_search_path(void); /** Load a DLL using LoadLibrary. * Only the system and program directories are searched. * * @param library_name The name of the DLL. * @return A handle to the DLL if found, NULL on failure. */ WS_DLL_PUBLIC void *ws_load_library(const gchar *library_name); /** Load wpcap.dll using g_module_open. * Only the system and program directories are searched. * * @return A handle to the DLL if found, NULL on failure. */ WS_DLL_PUBLIC GModule *load_wpcap_module(void); /** Create or open a "Wireshark is running" mutex. * Create or open a mutex which signals that Wireshark or its associated * executables is running. Used by the installer to test for a running application. */ WS_DLL_PUBLIC void create_app_running_mutex(void); /** Close our "Wireshark is running" mutex. */ WS_DLL_PUBLIC void close_app_running_mutex(void); /** Close a file descriptor if it is not open */ WS_DLL_PUBLIC int ws_close_if_possible(int fd); #else /* _WIN32 */ /* * The structure to pass to ws_fstat64(). */ #define ws_statb64 struct stat /* Not Windows, presumed to be UN*X-compatible */ #define ws_open open #define ws_rename rename #define ws_mkdir(dir,mode) mkdir(dir,mode) #define ws_stat64 stat #define ws_unlink unlink #define ws_remove remove #define ws_fopen fopen #define ws_freopen freopen typedef size_t ws_file_size_t; typedef ssize_t ws_file_ssize_t; #define ws_read read #define ws_write write #ifdef __cplusplus /* * Just in case this is used in a class with a close method or member. */ #define ws_close ::close #else #define ws_close close #endif #define ws_close_if_possible ws_close #define ws_dup dup #ifdef HAVE_FSEEKO #define ws_fseek64 fseeko /* AC_SYS_LARGEFILE should make off_t 64-bit */ #define ws_ftell64 ftello /* AC_SYS_LARGEFILE should make off_t 64-bit */ #else #define ws_fseek64(fh,offset,whence) fseek(fh,(long)(offset),whence) #define ws_ftell64 ftell #endif #define ws_fstat64 fstat /* AC_SYS_LARGEFILE should make off_t 64-bit */ #define ws_lseek64 lseek /* AC_SYS_LARGEFILE should make off_t 64-bit */ #define ws_fdopen fdopen #define ws_fileno fileno #define ws_isatty isatty #define ws_getc_unlocked getc_unlocked #define O_BINARY 0 /* Win32 needs the O_BINARY flag for open() */ /* Other CRT functions */ #define ws_getpid getpid #define ws_umask umask #endif /* _WIN32 */ /* directory handling */ #define WS_DIR GDir #define WS_DIRENT const char #define ws_dir_open g_dir_open #define ws_dir_read_name g_dir_read_name #define ws_dir_get_name(dirent) dirent #define ws_dir_rewind g_dir_rewind #define ws_dir_close g_dir_close /* XXX - remove include "sys/stat.h" from files that include this header */ /* XXX - update docs (e.g. README.developer) */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __FILE_UTIL_H__ */
C
wireshark/wsutil/filter_files.c
/* filter_files.c * Code for reading and writing the filters file. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <config.h> #define WS_LOG_DOMAIN LOG_DOMAIN_WSUTIL #include "filter_files.h" #include <stdio.h> #include <string.h> #include <errno.h> #include <wsutil/file_util.h> #include <wsutil/filesystem.h> #include <wsutil/report_message.h> #include <wsutil/wslog.h> #include <wsutil/ws_assert.h> /* * List of capture filters - saved. */ static GList *capture_filters = NULL; /* * List of display filters - saved. */ static GList *display_filters = NULL; /* * Read in a list of filters. * * On error, report the error via the UI. */ #define INIT_BUF_SIZE 128 static GList * add_filter_entry(GList *fl, const char *filt_name, const char *filt_expr) { filter_def *filt; filt = g_new(filter_def, 1); filt->name = g_strdup(filt_name); filt->strval = g_strdup(filt_expr); return g_list_prepend(fl, filt); } static void free_filter_entry(gpointer data) { filter_def *filt = (filter_def*)data; g_free(filt->name); g_free(filt->strval); g_free(filt); } void free_filter_lists(void) { if (capture_filters) { g_list_free_full(capture_filters, free_filter_entry); capture_filters = NULL; } if (display_filters) { g_list_free_full(display_filters, free_filter_entry); display_filters = NULL; } } static GList * remove_filter_entry(GList *fl, GList *fl_entry) { filter_def *filt; filt = (filter_def *) fl_entry->data; g_free(filt->name); g_free(filt->strval); g_free(filt); return g_list_remove_link(fl, fl_entry); } static int skip_whitespace(FILE *ff) { int c; while ((c = getc(ff)) != EOF && c != '\n' && g_ascii_isspace(c)) ; return c; } static int getc_crlf(FILE *ff) { int c; c = getc(ff); if (c == '\r') { /* Treat CR-LF at the end of a line like LF, so that if we're reading * a Windows-format file on UN*X, we handle it the same way we'd handle * a UN*X-format file. */ c = getc(ff); if (c != EOF && c != '\n') { /* Put back the character after the CR, and process the CR normally. */ ungetc(c, ff); c = '\r'; } } return c; } void read_filter_list(filter_list_type_t list_type) { const char *ff_name, *ff_description; char *ff_path; FILE *ff; GList **flpp; int c; char *filt_name, *filt_expr; int filt_name_len, filt_expr_len; int filt_name_index, filt_expr_index; int line = 1; switch (list_type) { case CFILTER_LIST: ff_name = CFILTER_FILE_NAME; ff_description = "capture"; flpp = &capture_filters; break; case DFILTER_LIST: ff_name = DFILTER_FILE_NAME; ff_description = "display"; flpp = &display_filters; break; default: ws_assert_not_reached(); return; } /* try to open personal "cfilters"/"dfilters" file */ ff_path = get_persconffile_path(ff_name, TRUE); if ((ff = ws_fopen(ff_path, "r")) == NULL) { /* * Did that fail because the file didn't exist? */ if (errno != ENOENT) { /* * No. Just give up. */ report_warning("Could not open your %s filter file\n\"%s\": %s.", ff_description, ff_path, g_strerror(errno)); g_free(ff_path); return; } /* * Yes. See if there's an "old style" personal "filters" file; if so, read it. * This means that a user will start out with their capture and * display filter lists being identical; each list may contain * filters that don't belong in that list. The user can edit * the filter lists, and delete the ones that don't belong in * a particular list. */ g_free(ff_path); ff_path = get_persconffile_path(FILTER_FILE_NAME, FALSE); if ((ff = ws_fopen(ff_path, "r")) == NULL) { /* * Did that fail because the file didn't exist? */ if (errno != ENOENT) { /* * No. Just give up. */ report_warning("Could not open your %s filter file\n\"%s\": %s.", ff_description, ff_path, g_strerror(errno)); g_free(ff_path); return; } /* * Try to open the global "cfilters/dfilters" file. */ g_free(ff_path); ff_path = get_datafile_path(ff_name); if ((ff = ws_fopen(ff_path, "r")) == NULL) { /* * Well, that didn't work, either. Just give up. * Report an error if the file existed but we couldn't open it. */ if (errno != ENOENT) { report_warning("Could not open your %s filter file\n\"%s\": %s.", ff_description, ff_path, g_strerror(errno)); } g_free(ff_path); return; } } } /* If we already have a list of filters, discard it. */ /* this should never happen - this function is called only once for each list! */ while(*flpp) { *flpp = remove_filter_entry(*flpp, g_list_first(*flpp)); } /* Allocate the filter name buffer. */ filt_name_len = INIT_BUF_SIZE; filt_name = (char *)g_malloc(filt_name_len + 1); filt_expr_len = INIT_BUF_SIZE; filt_expr = (char *)g_malloc(filt_expr_len + 1); for (line = 1; ; line++) { /* Lines in a filter file are of the form "name" expression where "name" is a name, in quotes - backslashes in the name escape the next character, so quotes and backslashes can appear in the name - and "expression" is a filter expression, not in quotes, running to the end of the line. */ /* Skip over leading white space, if any. */ c = skip_whitespace(ff); if (c == EOF) break; /* Nothing more to read */ if (c == '\n') continue; /* Blank line. */ /* "c" is the first non-white-space character. If it's not a quote, it's an error. */ if (c != '"') { ws_warning("'%s' line %d doesn't have a quoted filter name.", ff_path, line); while (c != '\n') c = getc(ff); /* skip to the end of the line */ continue; } /* Get the name of the filter. */ filt_name_index = 0; for (;;) { c = getc_crlf(ff); if (c == EOF || c == '\n') break; /* End of line - or end of file */ if (c == '"') { /* Closing quote. */ if (filt_name_index >= filt_name_len) { /* Filter name buffer isn't long enough; double its length. */ filt_name_len *= 2; filt_name = (char *)g_realloc(filt_name, filt_name_len + 1); } filt_name[filt_name_index] = '\0'; break; } if (c == '\\') { /* Next character is escaped */ c = getc_crlf(ff); if (c == EOF || c == '\n') break; /* End of line - or end of file */ } /* Add this character to the filter name string. */ if (filt_name_index >= filt_name_len) { /* Filter name buffer isn't long enough; double its length. */ filt_name_len *= 2; filt_name = (char *)g_realloc(filt_name, filt_name_len + 1); } filt_name[filt_name_index] = c; filt_name_index++; } if (c == EOF) { if (!ferror(ff)) { /* EOF, not error; no newline seen before EOF */ ws_warning("'%s' line %d doesn't have a newline.", ff_path, line); } break; /* nothing more to read */ } if (c != '"') { /* No newline seen before end-of-line */ ws_warning("'%s' line %d doesn't have a closing quote.", ff_path, line); continue; } /* Skip over separating white space, if any. */ c = skip_whitespace(ff); if (c == EOF) { if (!ferror(ff)) { /* EOF, not error; no newline seen before EOF */ ws_warning("'%s' line %d doesn't have a newline.", ff_path, line); } break; /* nothing more to read */ } if (c == '\n') { /* No filter expression */ ws_warning("'%s' line %d doesn't have a filter expression.", ff_path, line); continue; } /* "c" is the first non-white-space character; it's the first character of the filter expression. */ filt_expr_index = 0; for (;;) { /* Add this character to the filter expression string. */ if (filt_expr_index >= filt_expr_len) { /* Filter expressioin buffer isn't long enough; double its length. */ filt_expr_len *= 2; filt_expr = (char *)g_realloc(filt_expr, filt_expr_len + 1); } filt_expr[filt_expr_index] = c; filt_expr_index++; /* Get the next character. */ c = getc_crlf(ff); if (c == EOF || c == '\n') break; } if (c == EOF) { if (!ferror(ff)) { /* EOF, not error; no newline seen before EOF */ ws_warning("'%s' line %d doesn't have a newline.", ff_path, line); } break; /* nothing more to read */ } /* We saw the ending newline; terminate the filter expression string */ if (filt_expr_index >= filt_expr_len) { /* Filter expressioin buffer isn't long enough; double its length. */ filt_expr_len *= 2; filt_expr = (char *)g_realloc(filt_expr, filt_expr_len + 1); } filt_expr[filt_expr_index] = '\0'; /* Add the new filter to the list of filters */ *flpp = add_filter_entry(*flpp, filt_name, filt_expr); } if (ferror(ff)) { report_warning("Error reading your %s filter file\n\"%s\": %s.", ff_description, ff_path, g_strerror(errno)); } g_free(ff_path); fclose(ff); g_free(filt_name); g_free(filt_expr); } /* * Get a pointer to a list of filters. */ static GList ** get_filter_list(filter_list_type_t list_type) { GList **flpp; switch (list_type) { case CFILTER_LIST: flpp = &capture_filters; break; case DFILTER_LIST: flpp = &display_filters; break; default: ws_assert_not_reached(); flpp = NULL; } return flpp; } /* * Get a pointer to the first entry in a filter list. */ GList * get_filter_list_first(filter_list_type_t list_type) { GList **flpp; flpp = get_filter_list(list_type); return g_list_first(*flpp); } /* * Add a new filter to the end of a list. * Returns a pointer to the newly-added entry. */ GList * add_to_filter_list(filter_list_type_t list_type, const char *name, const char *expression) { GList **flpp; flpp = get_filter_list(list_type); *flpp = add_filter_entry(*flpp, name, expression); return g_list_last(*flpp); } /* * Remove a filter from a list. */ void remove_from_filter_list(filter_list_type_t list_type, GList *fl_entry) { GList **flpp; flpp = get_filter_list(list_type); *flpp = remove_filter_entry(*flpp, fl_entry); } /* * Write out a list of filters. * * On error, report the error via the UI. */ void save_filter_list(filter_list_type_t list_type) { char *pf_dir_path; const gchar *ff_name, *ff_description; gchar *ff_path, *ff_path_new; GList *fl; GList *flpp; filter_def *filt; FILE *ff; guchar *p, c; switch (list_type) { case CFILTER_LIST: ff_name = CFILTER_FILE_NAME; ff_description = "capture"; fl = capture_filters; break; case DFILTER_LIST: ff_name = DFILTER_FILE_NAME; ff_description = "display"; fl = display_filters; break; default: ws_assert_not_reached(); return; } /* Create the directory that holds personal configuration files, if necessary. */ if (create_persconffile_dir(&pf_dir_path) == -1) { report_failure("Can't create directory\n\"%s\"\nfor filter files: %s.", pf_dir_path, g_strerror(errno)); g_free(pf_dir_path); return; } ff_path = get_persconffile_path(ff_name, TRUE); /* Write to "XXX.new", and rename if that succeeds. That means we don't trash the file if we fail to write it out completely. */ ff_path_new = ws_strdup_printf("%s.new", ff_path); if ((ff = ws_fopen(ff_path_new, "w")) == NULL) { /* We had an error saving the filter. */ report_failure("Error saving your %s filter file\nCouldn't open \"%s\": %s.", ff_description, ff_path_new, g_strerror(errno)); g_free(ff_path_new); g_free(ff_path); return; } flpp = g_list_first(fl); while (flpp) { filt = (filter_def *) flpp->data; /* Write out the filter name as a quoted string; escape any quotes or backslashes. */ putc('"', ff); for (p = (guchar *)filt->name; (c = *p) != '\0'; p++) { if (c == '"' || c == '\\') putc('\\', ff); putc(c, ff); } putc('"', ff); /* Separate the filter name and value with a space. */ putc(' ', ff); /* Write out the filter expression and a newline. */ fprintf(ff, "%s\n", filt->strval); if (ferror(ff)) { report_failure("Error saving your %s filter file\nWrite to \"%s\" failed: %s.", ff_description, ff_path_new, g_strerror(errno)); fclose(ff); ws_unlink(ff_path_new); g_free(ff_path_new); g_free(ff_path); return; } flpp = flpp->next; } if (fclose(ff) == EOF) { report_failure("Error saving your %s filter file\nWrite to \"%s\" failed: %s.", ff_description, ff_path_new, g_strerror(errno)); ws_unlink(ff_path_new); g_free(ff_path_new); g_free(ff_path); return; } #ifdef _WIN32 /* ANSI C doesn't say whether "rename()" removes the target if it exists; the Win32 call to rename files doesn't do so, which I infer is the reason why the MSVC++ "rename()" doesn't do so. We must therefore remove the target file first, on Windows. XXX - ws_rename() should be ws_stdio_rename() on Windows, and ws_stdio_rename() uses MoveFileEx() with MOVEFILE_REPLACE_EXISTING, so it should remove the target if it exists, so this stuff shouldn't be necessary. Perhaps it dates back to when we were calling rename(), with that being a wrapper around Microsoft's _rename(), which didn't remove the target. */ if (ws_remove(ff_path) < 0 && errno != ENOENT) { /* It failed for some reason other than "it's not there"; if it's not there, we don't need to remove it, so we just drive on. */ report_failure("Error saving your %s filter file\nCouldn't remove \"%s\": %s.", ff_description, ff_path, g_strerror(errno)); ws_unlink(ff_path_new); g_free(ff_path_new); g_free(ff_path); return; } #endif if (ws_rename(ff_path_new, ff_path) < 0) { report_failure("Error saving your %s filter file\nCouldn't rename \"%s\" to \"%s\": %s.", ff_description, ff_path_new, ff_path, g_strerror(errno)); ws_unlink(ff_path_new); g_free(ff_path_new); g_free(ff_path); return; } g_free(ff_path_new); g_free(ff_path); }
C/C++
wireshark/wsutil/filter_files.h
/** @file * * Declarations of routines for reading and writing the filters file. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __FILTER_FILES_H__ #define __FILTER_FILES_H__ #include <wireshark.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Old filter file name. */ #define FILTER_FILE_NAME "filters" /* * Capture filter file name. */ #define CFILTER_FILE_NAME "cfilters" /* * Display filter file name. */ #define DFILTER_FILE_NAME "dfilters" /* * Filter lists. */ typedef enum { CFILTER_LIST, /* capture filter list - saved */ DFILTER_LIST /* display filter list - saved */ } filter_list_type_t; /* * Item in a list of filters. */ typedef struct { char *name; /* filter name */ char *strval; /* filter expression */ } filter_def; /* * Read in a list of filters. * * On error, report the error via the UI. */ WS_DLL_PUBLIC void read_filter_list(filter_list_type_t list_type); /* * Get a pointer to the first entry in a filter list. */ WS_DLL_PUBLIC GList *get_filter_list_first(filter_list_type_t list); /* * Add a new filter to the end of a list. * Returns a pointer to the newly-added entry. */ WS_DLL_PUBLIC GList *add_to_filter_list(filter_list_type_t list, const char *name, const char *expression); /* * Remove a filter from a list. */ WS_DLL_PUBLIC void remove_from_filter_list(filter_list_type_t list, GList *fl_entry); /* * Write out a list of filters. * * On error, report the error via the UI. */ WS_DLL_PUBLIC void save_filter_list(filter_list_type_t list_type); /* * Free all filter lists */ WS_DLL_PUBLIC void free_filter_lists(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __FILTER_FILES_H__ */
C
wireshark/wsutil/g711.c
/* * This source code is a product of Sun Microsystems, Inc. and is provided * for unrestricted use. Users may copy or modify this source code without * charge. * * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun source code is provided with no support and without any obligation on * the part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ #include "g711.h" /* * g711.c * * u-law, A-law and linear PCM conversions. */ #define SIGN_BIT (0x80) /* Sign bit for a A-law byte. */ #define QUANT_MASK (0xf) /* Quantization field mask. */ #define NSEGS (8) /* Number of A-law segments. */ #define SEG_SHIFT (4) /* Left shift for segment number. */ #define SEG_MASK (0x70) /* Segment field mask. */ static short seg_end[8] = {0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF}; /* copy from CCITT G.711 specifications */ unsigned char _u2a[128] = { /* u- to A-law conversions */ 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 29, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 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}; unsigned char _a2u[128] = { /* A- to u-law conversions */ 1, 3, 5, 7, 9, 11, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 48, 49, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 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}; static int search( int val, short *table, int size) { int i; for (i = 0; i < size; i++) { if (val <= *table++) return (i); } return (size); } /* * linear2alaw() - Convert a 16-bit linear PCM value to 8-bit A-law * * linear2alaw() accepts an 16-bit integer and encodes it as A-law data. * * Linear Input Code Compressed Code * ------------------------ --------------- * 0000000wxyza 000wxyz * 0000001wxyza 001wxyz * 000001wxyzab 010wxyz * 00001wxyzabc 011wxyz * 0001wxyzabcd 100wxyz * 001wxyzabcde 101wxyz * 01wxyzabcdef 110wxyz * 1wxyzabcdefg 111wxyz * * For further information see John C. Bellamy's Digital Telephony, 1982, * John Wiley & Sons, pps 98-111 and 472-476. */ unsigned char linear2alaw( int pcm_val) /* 2's complement (16-bit range) */ { int mask; int seg; unsigned char aval; if (pcm_val >= 0) { mask = 0xD5; /* sign (7th) bit = 1 */ } else { mask = 0x55; /* sign bit = 0 */ pcm_val = -pcm_val - 8; } /* Convert the scaled magnitude to segment number. */ seg = search(pcm_val, seg_end, 8); /* Combine the sign, segment, and quantization bits. */ if (seg >= 8) /* out of range, return maximum value. */ return (0x7F ^ mask); else { aval = seg << SEG_SHIFT; if (seg < 2) aval |= (pcm_val >> 4) & QUANT_MASK; else aval |= (pcm_val >> (seg + 3)) & QUANT_MASK; return (aval ^ mask); } } /* * alaw2linear() - Convert an A-law value to 16-bit linear PCM * */ int alaw2linear( unsigned char a_val) { int t; int seg; /*printf(" vrednost a_val %X ", a_val);*/ a_val ^= 0x55; t = (a_val & QUANT_MASK) << 4; seg = ((unsigned)a_val & SEG_MASK) >> SEG_SHIFT; switch (seg) { case 0: t += 8; break; case 1: t += 0x108; break; default: t += 0x108; t <<= seg - 1; } /*printf("izracunan int %d in njegov hex %X \n", t,t);*/ return ((a_val & SIGN_BIT) ? t : -t); } #define BIAS (0x84) /* Bias for linear code. */ /* * linear2ulaw() - Convert a linear PCM value to u-law * * In order to simplify the encoding process, the original linear magnitude * is biased by adding 33 which shifts the encoding range from (0 - 8158) to * (33 - 8191). The result can be seen in the following encoding table: * * Biased Linear Input Code Compressed Code * ------------------------ --------------- * 00000001wxyza 000wxyz * 0000001wxyzab 001wxyz * 000001wxyzabc 010wxyz * 00001wxyzabcd 011wxyz * 0001wxyzabcde 100wxyz * 001wxyzabcdef 101wxyz * 01wxyzabcdefg 110wxyz * 1wxyzabcdefgh 111wxyz * * Each biased linear code has a leading 1 which identifies the segment * number. The value of the segment number is equal to 7 minus the number * of leading 0's. The quantization interval is directly available as the * four bits wxyz. * The trailing bits (a - h) are ignored. * * Ordinarily the complement of the resulting code word is used for * transmission, and so the code word is complemented before it is returned. * * For further information see John C. Bellamy's Digital Telephony, 1982, * John Wiley & Sons, pps 98-111 and 472-476. */ unsigned char linear2ulaw( int pcm_val) /* 2's complement (16-bit range) */ { int mask; int seg; unsigned char uval; /* Get the sign and the magnitude of the value. */ if (pcm_val < 0) { pcm_val = BIAS - pcm_val; mask = 0x7F; } else { pcm_val += BIAS; mask = 0xFF; } /* Convert the scaled magnitude to segment number. */ seg = search(pcm_val, seg_end, 8); /* * Combine the sign, segment, quantization bits; * and complement the code word. */ if (seg >= 8) /* out of range, return maximum value. */ return (0x7F ^ mask); else { uval = (seg << 4) | ((pcm_val >> (seg + 3)) & 0xF); return (uval ^ mask); } } /* * ulaw2linear() - Convert a u-law value to 16-bit linear PCM * * First, a biased linear code is derived from the code word. An unbiased * output can then be obtained by subtracting 33 from the biased code. * * Note that this function expects to be passed the complement of the * original code word. This is in keeping with ISDN conventions. */ int ulaw2linear( unsigned char u_val) { int t; /* Complement to obtain normal u-law value. */ u_val = ~u_val; /* * Extract and bias the quantization bits. Then * shift up by the segment number and subtract out the bias. */ t = ((u_val & QUANT_MASK) << 3) + BIAS; t <<= ((unsigned)u_val & SEG_MASK) >> SEG_SHIFT; return ((u_val & SIGN_BIT) ? (BIAS - t) : (t - BIAS)); } /* A-law to u-law conversion */ /* unsigned char * alaw2ulaw( * unsigned char aval) * { * aval &= 0xff; * return ((aval & 0x80) ? (0xFF ^ _a2u[aval ^ 0xD5]) : * (0x7F ^ _a2u[aval ^ 0x55])); * } */ /* u-law to A-law conversion */ /* unsigned char * ulaw2alaw( * unsigned char uval) * { * uval &= 0xff; * return ((uval & 0x80) ? (0xD5 ^ (_u2a[0xFF ^ uval] - 1)) : * (0x55 ^ (_u2a[0x7F ^ uval] - 1))); * } */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/g711.h
/** @file * * Definitions for routines for u-law, A-law and linear PCM conversions * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __G711_H__ #define __G711_H__ #include "ws_symbol_export.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ WS_DLL_PUBLIC unsigned char linear2alaw( int ); WS_DLL_PUBLIC int alaw2linear( unsigned char ); WS_DLL_PUBLIC unsigned char linear2ulaw( int ); WS_DLL_PUBLIC int ulaw2linear( unsigned char ); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __G711_H__ */
C/C++
wireshark/wsutil/glib-compat.h
/** @file * * Definitions to provide some functions that are not present in older * GLIB versions we support (currently down to 2.50) * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef GLIB_COMPAT_H #define GLIB_COMPAT_H #include "ws_symbol_export.h" #include "ws_attributes.h" #include <glib.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #if !GLIB_CHECK_VERSION(2, 68, 0) static inline gpointer g_memdup2(gconstpointer mem, gsize byte_size) { gpointer new_mem; if (mem && byte_size != 0) { new_mem = g_malloc(byte_size); memcpy(new_mem, mem, byte_size); } else new_mem = NULL; return new_mem; } #endif #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* GLIB_COMPAT_H */
C
wireshark/wsutil/inet_addr.c
/* inet_addr.c * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #define WS_LOG_DOMAIN LOG_DOMAIN_WSUTIL #include "inet_addr.h" #include <errno.h> #include <string.h> #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #include <sys/types.h> #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> /* needed to define AF_ values on UNIX */ #endif #ifdef _WIN32 #include <ws2tcpip.h> /* indirectly defines AF_ values on Windows */ #define _NTOP_SRC_CAST_ (PVOID) #else #define _NTOP_SRC_CAST_ #endif #include "str_util.h" /* * We assume and require an inet_pton/inet_ntop that supports AF_INET * and AF_INET6. */ static inline bool inet_pton_internal(int af, const char *src, void *dst, size_t dst_size, const char *af_str) { int ret = inet_pton(af, src, dst); if (ret < 0) { int err = errno; ws_log(WS_LOG_DOMAIN, LOG_LEVEL_CRITICAL, "inet_pton: %s (%d): %s", af_str, af, g_strerror(err)); memset(dst, 0, dst_size); errno = err; return false; } /* ret == 0 invalid src representation, ret == 1 success. */ return ret == 1; } static inline const char * inet_ntop_internal(int af, const void *src, char *dst, size_t dst_size, const char *af_str) { /* Add a cast to ignore 64-to-32 bit narrowing warnings with some * compilers (POSIX uses socklen_t instead of size_t). */ const char *ret = inet_ntop(af, _NTOP_SRC_CAST_ src, dst, (unsigned int)dst_size); if (ret == NULL) { int err = errno; char errbuf[16]; ws_log(WS_LOG_DOMAIN, LOG_LEVEL_CRITICAL, "inet_ntop: %s (%d): %s", af_str, af, g_strerror(err)); /* set result to something that can't be confused with a valid conversion */ (void)g_strlcpy(dst, ws_strerrorname_r(err, errbuf, sizeof(errbuf)), dst_size); errno = err; return dst; } return dst; } const char * ws_inet_ntop4(const void *src, char *dst, size_t dst_size) { return inet_ntop_internal(AF_INET, src, dst, dst_size, "AF_INET"); } bool ws_inet_pton4(const char *src, ws_in4_addr *dst) { return inet_pton_internal(AF_INET, src, dst, sizeof(*dst), "AF_INET"); } const char * ws_inet_ntop6(const void *src, char *dst, size_t dst_size) { return inet_ntop_internal(AF_INET6, src, dst, dst_size, "AF_INET6"); } bool ws_inet_pton6(const char *src, ws_in6_addr *dst) { return inet_pton_internal(AF_INET6, src, dst, sizeof(*dst), "AF_INET6"); }
C/C++
wireshark/wsutil/inet_addr.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_INET_ADDR_H__ #define __WS_INET_ADDR_H__ #include <wireshark.h> #include "inet_ipv4.h" #include "inet_ipv6.h" /* * These are the values specified by RFC 2133 and its successors for * INET_ADDRSTRLEN and INET6_ADDRSTRLEN. * * On UN*X systems, INET_ADDRSTRLEN and INET6_ADDRSTRLEN are defined * to the values from RFC 2133 and its successors. * * However, on Windows: * * There are APIs RtlIpv4AddressToStringEx(), which converts an * IPv4 address *and transport-layer port* to the address in the * standard text form, followed by a colon and the port number, * and RtlIpv6AddressToStringEx(), which converts an IPv6 address * *and scope ID and transport-layer port* to the address in the * standard text form, followed by a percent sign and the scope * ID (with the address and scope ID in square brackets), followed * by a colon and the port number. * * Instead of defining INET_ADDRSTRLEN_EX as 22 and INET6_ADDRSTRLEN_EX * as 65, and saying *those* were the buffer sizes to use for * RtlIpv4AddressToStringEx() and RtlIpv6AddressToStringEx(), they * defined INET_ADDRSTRLEN to be 22 and INET6_ADDRSTRLEN to be 65 - and * recommend using those as the size for the buffers passed to * RtlIpv4AddressToStringEx() and RtlIpv6AddressToStringEx(). * * At least they document inet_ntop() as requiring a 16-byte or larger * buffer for IPv4 addresses and a 46-byte or larger buffer for * IPv6 addresses. For this reason, use hard-coded numeric constants rather than * INET_ADDRSTRLEN and INET6_ADDRSTRLEN. */ #define WS_INET_ADDRSTRLEN 16 #define WS_INET6_ADDRSTRLEN 46 #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * To check for errors set errno to zero before calling ws_inet_ntop{4,6}. * ENOSPC is set if the result exceeds the given buffer size. */ WS_DLL_PUBLIC WS_RETNONNULL const char * ws_inet_ntop4(const void *src, char *dst, size_t dst_size); WS_DLL_PUBLIC WS_RETNONNULL const char * ws_inet_ntop6(const void *src, char *dst, size_t dst_size); WS_DLL_PUBLIC bool ws_inet_pton4(const char *src, ws_in4_addr *dst); WS_DLL_PUBLIC bool ws_inet_pton6(const char *src, ws_in6_addr *dst); #ifdef __cplusplus } #endif /* __cplusplus */ #endif
C/C++
wireshark/wsutil/inet_ipv4.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __INET_IPV4_H__ #define __INET_IPV4_H__ #include <glib.h> typedef guint32 ws_in4_addr; /* 32 bit IPv4 address, in network byte order */ /* * We define these in *network byte order*, unlike the C library. Therefore * it uses a different prefix than INADDR_* to make the distinction more obvious. */ #define WS_IN4_LOOPBACK ((ws_in4_addr)GUINT32_TO_BE(0x7f000001)) /** * Unicast Local * Returns true if the address is in the 224.0.0.0/24 local network * control block */ #define in4_addr_is_local_network_control_block(addr) \ ((addr & 0xffffff00) == 0xe0000000) /** * Multicast * Returns true if the address is in the 224.0.0.0/4 network block */ #define in4_addr_is_multicast(addr) \ ((addr & 0xf0000000) == 0xe0000000) /** * Private address * Returns true if the address is in one of the three blocks reserved * for private IPv4 addresses by section 3 of RFC 1918, namely: * 10/8, 172.16/12, and 192.168/16 */ #define in4_addr_is_private(addr) \ (((addr & 0xff000000) == 0x0a000000) || \ ((addr & 0xfff00000) == 0xac100000) || \ ((addr & 0xffff0000) == 0xc0a80000)) /** * Link-local address * Returns true if the address is in the 169.254/16 network block */ #define in4_addr_is_link_local(addr) \ ((addr & 0xffff0000) == 0xa9fe0000) #endif
C/C++
wireshark/wsutil/inet_ipv6.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __INET_IPV6_H__ #define __INET_IPV6_H__ #include <glib.h> #define IPv6_ADDR_SIZE 16 #define IPv6_HDR_SIZE 40 #define IPv6_FRAGMENT_HDR_SIZE 8 typedef struct e_in6_addr { guint8 bytes[16]; /* 128 bit IPv6 address */ } ws_in6_addr; /* * Definition for internet protocol version 6. * RFC 2460 */ struct ws_ip6_hdr { guint32 ip6h_vc_flow; /* version, class, flow */ guint16 ip6h_plen; /* payload length */ guint8 ip6h_nxt; /* next header */ guint8 ip6h_hlim; /* hop limit */ ws_in6_addr ip6h_src; /* source address */ ws_in6_addr ip6h_dst; /* destination address */ }; /* * Extension Headers */ struct ip6_ext { guchar ip6e_nxt; guchar ip6e_len; }; /* Routing header */ struct ip6_rthdr { guint8 ip6r_nxt; /* next header */ guint8 ip6r_len; /* length in units of 8 octets */ guint8 ip6r_type; /* routing type */ guint8 ip6r_segleft; /* segments left */ /* followed by routing type specific data */ }; /* Type 0 Routing header */ struct ip6_rthdr0 { guint8 ip6r0_nxt; /* next header */ guint8 ip6r0_len; /* length in units of 8 octets */ guint8 ip6r0_type; /* always zero */ guint8 ip6r0_segleft; /* segments left */ guint8 ip6r0_reserved; /* reserved field */ guint8 ip6r0_slmap[3]; /* strict/loose bit map */ /* followed by up to 127 addresses */ ws_in6_addr ip6r0_addr[1]; }; /* Fragment header */ struct ip6_frag { guint8 ip6f_nxt; /* next header */ guint8 ip6f_reserved; /* reserved field */ guint16 ip6f_offlg; /* offset, reserved, and flag */ guint32 ip6f_ident; /* identification */ }; #define IP6F_OFF_MASK 0xfff8 /* mask out offset from _offlg */ #define IP6F_RESERVED_MASK 0x0006 /* reserved bits in ip6f_offlg */ #define IP6F_MORE_FRAG 0x0001 /* more-fragments flag */ /** * Unicast Scope * Note that we must check topmost 10 bits only, not 16 bits (see RFC2373). */ static inline gboolean in6_addr_is_linklocal(const ws_in6_addr *a) { return (a->bytes[0] == 0xfe) && ((a->bytes[1] & 0xc0) == 0x80); } static inline gboolean in6_addr_is_sitelocal(const ws_in6_addr *a) { return (a->bytes[0] == 0xfe) && ((a->bytes[1] & 0xc0) == 0xc0); } /** * Multicast */ static inline gboolean in6_addr_is_multicast(const ws_in6_addr *a) { return a->bytes[0] == 0xff; } #endif
C
wireshark/wsutil/interface.c
/* interface.c * Utility functions to get infos from interfaces * * Copyright 2016, Dario Lombardo * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "interface.h" #include <string.h> #include <wsutil/inet_addr.h> #include <sys/types.h> #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_IFADDRS_H #include <ifaddrs.h> #endif #ifdef _WIN32 #include <winsock2.h> #include <iphlpapi.h> #include <ws2tcpip.h> #endif #define WORKING_BUFFER_SIZE 15000 #ifdef HAVE_GETIFADDRS static GSList* local_interfaces_to_list_nix(void) { GSList *interfaces = NULL; struct ifaddrs *ifap; struct ifaddrs *ifa; int family; char ip[WS_INET6_ADDRSTRLEN]; if (getifaddrs(&ifap)) { goto end; } for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; memset(ip, 0x0, WS_INET6_ADDRSTRLEN); switch (family) { case AF_INET: { struct sockaddr_in *addr4 = (struct sockaddr_in *)ifa->ifa_addr; ws_inet_ntop4(&addr4->sin_addr, ip, sizeof(ip)); break; } case AF_INET6: { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)ifa->ifa_addr; ws_inet_ntop6(&addr6->sin6_addr, ip, sizeof(ip)); break; } default: break; } /* skip loopback addresses */ if (!g_strcmp0(ip, "127.0.0.1") || !g_strcmp0(ip, "::1")) continue; if (*ip) { interfaces = g_slist_prepend(interfaces, g_strdup(ip)); } } freeifaddrs(ifap); end: return interfaces; } #endif /* HAVE_GETIFADDRS */ #ifdef _WIN32 static GSList* local_interfaces_to_list_win(void) { GSList *interfaces = NULL; PIP_ADAPTER_ADDRESSES pAddresses = NULL; ULONG outBufLen = WORKING_BUFFER_SIZE; ULONG family = AF_UNSPEC; PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL; char ip[100]; guint iplen = 100; pAddresses = (IP_ADAPTER_ADDRESSES *)g_malloc0(outBufLen); if (pAddresses == NULL) return NULL; if (GetAdaptersAddresses(family, 0, NULL, pAddresses, &outBufLen) != NO_ERROR) goto end; pCurrAddresses = pAddresses; while (pCurrAddresses) { for (pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast != NULL; pUnicast = pUnicast->Next) { if (pUnicast->Address.lpSockaddr->sa_family == AF_INET) { SOCKADDR_IN* sa_in = (SOCKADDR_IN *)pUnicast->Address.lpSockaddr; ws_inet_ntop4(&(sa_in->sin_addr), ip, iplen); if (!g_strcmp0(ip, "127.0.0.1")) continue; if (*ip) interfaces = g_slist_prepend(interfaces, g_strdup(ip)); } if (pUnicast->Address.lpSockaddr->sa_family == AF_INET6) { SOCKADDR_IN6* sa_in6 = (SOCKADDR_IN6 *)pUnicast->Address.lpSockaddr; ws_inet_ntop6(&(sa_in6->sin6_addr), ip, iplen); if (!g_strcmp0(ip, "::1")) continue; if (*ip) interfaces = g_slist_prepend(interfaces, g_strdup(ip)); } } pCurrAddresses = pCurrAddresses->Next; } end: g_free(pAddresses); return interfaces; } #endif /* _WIN32 */ GSList* local_interfaces_to_list(void) { #if defined(_WIN32) return local_interfaces_to_list_win(); #elif defined(HAVE_GETIFADDRS) return local_interfaces_to_list_nix(); #else return NULL; #endif } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=4 tabstop=8 noexpandtab: * :indentSize=4:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/interface.h
/** @file * Utility functions to get infos from interfaces * * Copyright 2016, Dario Lombardo * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef _INTERFACE_H #define _INTERFACE_H #include <glib.h> #include "ws_symbol_export.h" /* Return a list of IPv4/IPv6 addresses for local interfaces */ WS_DLL_PUBLIC GSList* local_interfaces_to_list(void); #endif /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=4 tabstop=8 noexpandtab: * :indentSize=4:tabSize=8:noTabs=false: */
C
wireshark/wsutil/introspection.c
/* * Copyright 2021, João Valverde <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "introspection.h" #include <string.h> #include <stdlib.h> static int compare_enum(const void *needle, const void *memb) { return strcmp(needle, ((const ws_enum_t *)memb)->symbol); } const ws_enum_t * ws_enums_bsearch(const ws_enum_t *enums, size_t count, const char *needle) { return bsearch(needle, enums, count, sizeof(ws_enum_t), compare_enum); }
C/C++
wireshark/wsutil/introspection.h
/** @file * Copyright 2021, João Valverde <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef _INTROSPECTION_H_ #define _INTROSPECTION_H_ #include <stddef.h> #include <ws_symbol_export.h> typedef struct { const char *symbol; int value; } ws_enum_t; /** Performs a binary search for the magic constant "needle". */ WS_DLL_PUBLIC const ws_enum_t * ws_enums_bsearch(const ws_enum_t *enums, size_t count, const char *needle); #endif
C
wireshark/wsutil/jsmn.c
/* Copyright (c) 2010 Serge A. Zaitsev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "jsmn.h" /** * Allocates a fresh unused token from the token pull. */ static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *tok; if (parser->toknext >= num_tokens) { return NULL; } tok = &tokens[parser->toknext++]; tok->start = tok->end = -1; tok->size = 0; #ifdef JSMN_PARENT_LINKS tok->parent = -1; #endif return tok; } /** * Fills token type and boundaries. */ static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, int start, int end) { token->type = type; token->start = start; token->end = end; token->size = 0; } /** * Fills next available token with JSON primitive. */ static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *token; int start; start = parser->pos; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { switch (js[parser->pos]) { #ifndef JSMN_STRICT /* In strict mode primitive must be followed by "," or "}" or "]" */ case ':': #endif case '\t' : case '\r' : case '\n' : case ' ' : case ',' : case ']' : case '}' : goto found; } if (js[parser->pos] < 32 || js[parser->pos] >= 127) { parser->pos = start; return JSMN_ERROR_INVAL; } } #ifdef JSMN_STRICT /* In strict mode primitive must be followed by a comma/object/array */ parser->pos = start; return JSMN_ERROR_PART; #endif found: if (tokens == NULL) { parser->pos--; return 0; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; return JSMN_ERROR_NOMEM; } jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif parser->pos--; return 0; } /** * Fills next token with JSON string. */ static int jsmn_parse_string(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens) { jsmntok_t *token; int start = parser->pos; parser->pos++; /* Skip starting quote */ for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { char c = js[parser->pos]; /* Quote: end of string */ if (c == '\"') { if (tokens == NULL) { return 0; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; return JSMN_ERROR_NOMEM; } jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif return 0; } /* Backslash: Quoted symbol expected */ if (c == '\\' && parser->pos + 1 < len) { int i; parser->pos++; switch (js[parser->pos]) { /* Allowed escaped symbols */ case '\"': case '/' : case '\\' : case 'b' : case 'f' : case 'r' : case 'n' : case 't' : break; /* Allows escaped symbol \uXXXX */ case 'u': parser->pos++; for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { /* If it isn't a hex character we have an error */ if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ parser->pos = start; return JSMN_ERROR_INVAL; } parser->pos++; } parser->pos--; break; /* Unexpected symbol */ default: parser->pos = start; return JSMN_ERROR_INVAL; } } } parser->pos = start; return JSMN_ERROR_PART; } /** * Parse JSON string and fill tokens. */ int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, unsigned int num_tokens) { int r; int i; jsmntok_t *token; int count = parser->toknext; for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { char c; jsmntype_t type; c = js[parser->pos]; switch (c) { case '{': case '[': count++; if (tokens == NULL) { break; } token = jsmn_alloc_token(parser, tokens, num_tokens); if (token == NULL) return JSMN_ERROR_NOMEM; if (parser->toksuper != -1) { tokens[parser->toksuper].size++; #ifdef JSMN_PARENT_LINKS token->parent = parser->toksuper; #endif } token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); token->start = parser->pos; parser->toksuper = parser->toknext - 1; break; case '}': case ']': if (tokens == NULL) break; type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); #ifdef JSMN_PARENT_LINKS if (parser->toknext < 1) { return JSMN_ERROR_INVAL; } token = &tokens[parser->toknext - 1]; for (;;) { if (token->start != -1 && token->end == -1) { if (token->type != type) { return JSMN_ERROR_INVAL; } token->end = parser->pos + 1; parser->toksuper = token->parent; break; } if (token->parent == -1) { break; } token = &tokens[token->parent]; } #else for (i = parser->toknext - 1; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { if (token->type != type) { return JSMN_ERROR_INVAL; } parser->toksuper = -1; token->end = parser->pos + 1; break; } } /* Error if unmatched closing bracket */ if (i == -1) return JSMN_ERROR_INVAL; for (; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { parser->toksuper = i; break; } } #endif break; case '\"': r = jsmn_parse_string(parser, js, len, tokens, num_tokens); if (r < 0) return r; count++; if (parser->toksuper != -1 && tokens != NULL) tokens[parser->toksuper].size++; break; case '\t' : case '\r' : case '\n' : case ' ': break; case ':': parser->toksuper = parser->toknext - 1; break; case ',': if (tokens != NULL && parser->toksuper != -1 && tokens[parser->toksuper].type != JSMN_ARRAY && tokens[parser->toksuper].type != JSMN_OBJECT) { #ifdef JSMN_PARENT_LINKS parser->toksuper = tokens[parser->toksuper].parent; #else for (i = parser->toknext - 1; i >= 0; i--) { if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { if (tokens[i].start != -1 && tokens[i].end == -1) { parser->toksuper = i; break; } } } #endif } break; #ifdef JSMN_STRICT /* In strict mode primitives are: numbers and booleans */ case '-': case '0': case '1' : case '2': case '3' : case '4': case '5': case '6': case '7' : case '8': case '9': case 't': case 'f': case 'n' : /* And they must not be keys of the object */ if (tokens != NULL && parser->toksuper != -1) { jsmntok_t *t = &tokens[parser->toksuper]; if (t->type == JSMN_OBJECT || (t->type == JSMN_STRING && t->size != 0)) { return JSMN_ERROR_INVAL; } } #else /* In non-strict mode every unquoted value is a primitive */ default: #endif r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); if (r < 0) return r; count++; if (parser->toksuper != -1 && tokens != NULL) tokens[parser->toksuper].size++; break; #ifdef JSMN_STRICT /* Unexpected char in strict mode */ default: return JSMN_ERROR_INVAL; #endif } } if (tokens != NULL) { for (i = parser->toknext - 1; i >= 0; i--) { /* Unmatched opened object or array */ if (tokens[i].start != -1 && tokens[i].end == -1) { return JSMN_ERROR_PART; } } } return count; } /** * Creates a new parser based over a given buffer with an array of tokens * available. */ void jsmn_init(jsmn_parser *parser) { parser->pos = 0; parser->toknext = 0; parser->toksuper = -1; }
C/C++
wireshark/wsutil/jsmn.h
/** @file Copyright (c) 2010 Serge A. Zaitsev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __JSMN_H_ #define __JSMN_H_ #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /** * JSON type identifier. Basic types are: * o Object * o Array * o String * o Other primitive: number, boolean (true/false) or null */ typedef enum { JSMN_UNDEFINED = 0, JSMN_OBJECT = 1, JSMN_ARRAY = 2, JSMN_STRING = 3, JSMN_PRIMITIVE = 4 } jsmntype_t; enum jsmnerr { /* Not enough tokens were provided */ JSMN_ERROR_NOMEM = -1, /* Invalid character inside JSON string */ JSMN_ERROR_INVAL = -2, /* The string is not a full JSON packet, more bytes expected */ JSMN_ERROR_PART = -3 }; /** * JSON token description. * type type (object, array, string etc.) * start start position in JSON data string * end end position in JSON data string */ typedef struct { jsmntype_t type; int start; int end; int size; #ifdef JSMN_PARENT_LINKS int parent; #endif } jsmntok_t; /** * JSON parser. Contains an array of token blocks available. Also stores * the string being parsed now and current position in that string */ typedef struct { unsigned int pos; /* offset in the JSON string */ unsigned int toknext; /* next token to allocate */ int toksuper; /* superior token node, e.g parent object or array */ } jsmn_parser; /** * Create JSON parser over an array of tokens */ void jsmn_init(jsmn_parser *parser); /** * Run JSON parser. It parses a JSON data string into and array of tokens, each describing * a single JSON object. */ int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, unsigned int num_tokens); #ifdef __cplusplus } #endif #endif /* __JSMN_H_ */
C
wireshark/wsutil/json_dumper.c
/* json_dumper.c * Routines for serializing data as JSON. * * Copyright 2018, Peter Wu <[email protected]> * Copyright (C) 2016 Jakub Zawadzki * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "json_dumper.h" #define WS_LOG_DOMAIN LOG_DOMAIN_WSUTIL #include <math.h> #include <wsutil/wslog.h> /* * json_dumper.state[current_depth] describes a nested element: * - type: none/object/array/non-base64 value/base64 value * - has_name: Whether the object member name was set. * * (A base64 value isn't really a nested element, but that's a * convenient way of handling them, with a begin call that opens * the string with a double-quote, one or more calls to convert * raw bytes to base64 and add them to the value, and an end call * that finishes the base64 encoding, adds any remaining raw bytes * in base64 encoding, and closes the string with a double-quote.) */ enum json_dumper_element_type { JSON_DUMPER_TYPE_NONE = 0, JSON_DUMPER_TYPE_VALUE = 1, JSON_DUMPER_TYPE_OBJECT = 2, JSON_DUMPER_TYPE_ARRAY = 3, JSON_DUMPER_TYPE_BASE64 = 4, }; #define JSON_DUMPER_TYPE(state) ((enum json_dumper_element_type)((state) & 7)) #define JSON_DUMPER_HAS_NAME (1 << 3) static const char *json_dumper_element_type_names[] = { [JSON_DUMPER_TYPE_NONE] = "none", [JSON_DUMPER_TYPE_VALUE] = "value", [JSON_DUMPER_TYPE_OBJECT] = "object", [JSON_DUMPER_TYPE_ARRAY] = "array", [JSON_DUMPER_TYPE_BASE64] = "base64" }; #define NUM_JSON_DUMPER_ELEMENT_TYPE_NAMES (sizeof json_dumper_element_type_names / sizeof json_dumper_element_type_names[0]) #define JSON_DUMPER_FLAGS_ERROR (1 << 16) /* Output flag: an error occurred. */ enum json_dumper_change { JSON_DUMPER_BEGIN, JSON_DUMPER_END, JSON_DUMPER_SET_NAME, JSON_DUMPER_SET_VALUE, JSON_DUMPER_WRITE_BASE64, JSON_DUMPER_FINISH, }; /* JSON Dumper putc */ static void jd_putc(const json_dumper *dumper, char c) { if (dumper->output_file) { fputc(c, dumper->output_file); } if (dumper->output_string) { g_string_append_c(dumper->output_string, c); } } /* JSON Dumper puts */ static void jd_puts(const json_dumper *dumper, const char *s) { if (dumper->output_file) { fputs(s, dumper->output_file); } if (dumper->output_string) { g_string_append(dumper->output_string, s); } } static void jd_puts_len(const json_dumper *dumper, const char *s, gsize len) { if (dumper->output_file) { fwrite(s, 1, len, dumper->output_file); } if (dumper->output_string) { g_string_append_len(dumper->output_string, s, len); } } static void jd_vprintf(const json_dumper *dumper, const char *format, va_list args) { if (dumper->output_file) { vfprintf(dumper->output_file, format, args); } if (dumper->output_string) { g_string_append_vprintf(dumper->output_string, format, args); } } static void json_puts_string(const json_dumper *dumper, const char *str, gboolean dot_to_underscore) { if (!str) { jd_puts(dumper, "null"); return; } static const char json_cntrl[0x20][6] = { "u0000", "u0001", "u0002", "u0003", "u0004", "u0005", "u0006", "u0007", "b", "t", "n", "u000b", "f", "r", "u000e", "u000f", "u0010", "u0011", "u0012", "u0013", "u0014", "u0015", "u0016", "u0017", "u0018", "u0019", "u001a", "u001b", "u001c", "u001d", "u001e", "u001f" }; jd_putc(dumper, '"'); for (int i = 0; str[i]; i++) { if ((guint)str[i] < 0x20) { jd_putc(dumper, '\\'); jd_puts(dumper, json_cntrl[(guint)str[i]]); } else if (i > 0 && str[i - 1] == '<' && str[i] == '/') { // Convert </script> to <\/script> to avoid breaking web pages. jd_puts(dumper, "\\/"); } else { if (str[i] == '\\' || str[i] == '"') { jd_putc(dumper, '\\'); } if (dot_to_underscore && str[i] == '.') jd_putc(dumper, '_'); else jd_putc(dumper, str[i]); } } jd_putc(dumper, '"'); } static inline guint8 json_dumper_get_prev_state(json_dumper *dumper) { guint depth = dumper->current_depth; return depth != 0 ? dumper->state[depth - 1] : 0; } static inline guint8 json_dumper_get_curr_state(json_dumper *dumper) { guint depth = dumper->current_depth; return dumper->state[depth]; } /** * Called when a programming error is encountered where the JSON manipulation * state got corrupted. This could happen when pairing the wrong begin/end * calls, when writing multiple values for the same object, etc. */ static void json_dumper_bad(json_dumper *dumper, const char *what) { dumper->flags |= JSON_DUMPER_FLAGS_ERROR; if ((dumper->flags & JSON_DUMPER_FLAGS_NO_DEBUG)) { /* Console output can be slow, disable log calls to speed up fuzzing. */ /* * XXX - should this call abort()? If that flag isn't set, * ws_error() wou;d call it; is there any point in continuing * to do anything if we get here when fuzzing? */ return; } if (dumper->output_file) { fflush(dumper->output_file); } char unknown_curr_type_name[10+1]; char unknown_prev_type_name[10+1]; const char *curr_type_name, *prev_type_name; guint8 curr_state = json_dumper_get_curr_state(dumper); guint8 curr_type = JSON_DUMPER_TYPE(curr_state); if (curr_type < NUM_JSON_DUMPER_ELEMENT_TYPE_NAMES) { curr_type_name = json_dumper_element_type_names[curr_type]; } else { snprintf(unknown_curr_type_name, sizeof unknown_curr_type_name, "%u", curr_type); curr_type_name = unknown_curr_type_name; } if (dumper->current_depth != 0) { guint8 prev_state = json_dumper_get_prev_state(dumper); guint8 prev_type = JSON_DUMPER_TYPE(prev_state); if (prev_type < NUM_JSON_DUMPER_ELEMENT_TYPE_NAMES) { prev_type_name = json_dumper_element_type_names[prev_type]; } else { snprintf(unknown_prev_type_name, sizeof unknown_prev_type_name, "%u", prev_type); prev_type_name = unknown_prev_type_name; } } else { prev_type_name = "(none)"; } ws_error("json_dumper error: %s: current stack depth %u, current type %s, previous_type %s", what, dumper->current_depth, curr_type_name, prev_type_name); /* NOTREACHED */ } static inline gboolean json_dumper_stack_would_overflow(json_dumper *dumper) { if (dumper->current_depth + 1 >= JSON_DUMPER_MAX_DEPTH) { json_dumper_bad(dumper, "JSON dumper stack overflow"); return TRUE; } return FALSE; } static inline gboolean json_dumper_stack_would_underflow(json_dumper *dumper) { if (dumper->current_depth == 0) { json_dumper_bad(dumper, "JSON dumper stack underflow"); return TRUE; } return FALSE; } /** * Checks that the dumper has not already had an error. Fail, and * return FALSE, to tell our caller not to do any more work, if it * has. */ static gboolean json_dumper_check_previous_error(json_dumper *dumper) { if ((dumper->flags & JSON_DUMPER_FLAGS_ERROR)) { json_dumper_bad(dumper, "previous corruption detected"); return FALSE; } return TRUE; } static void print_newline_indent(const json_dumper *dumper, guint depth) { if ((dumper->flags & JSON_DUMPER_FLAGS_PRETTY_PRINT)) { jd_putc(dumper, '\n'); for (guint i = 0; i < depth; i++) { jd_puts(dumper, " "); } } } /** * Prints commas, newlines and indentation (if necessary). Used for array * values, object names and normal values (strings, etc.). */ static void prepare_token(json_dumper *dumper) { if (dumper->current_depth == 0) { // not part of an array or object. return; } guint8 prev_state = dumper->state[dumper->current_depth - 1]; // While processing the object value, reset the key state as it is consumed. dumper->state[dumper->current_depth - 1] &= ~JSON_DUMPER_HAS_NAME; switch (JSON_DUMPER_TYPE(prev_state)) { case JSON_DUMPER_TYPE_OBJECT: if ((prev_state & JSON_DUMPER_HAS_NAME)) { // Object key already set, value follows. No indentation needed. return; } break; case JSON_DUMPER_TYPE_ARRAY: break; default: // Initial values do not need indentation. return; } guint8 curr_state = json_dumper_get_curr_state(dumper); if (curr_state != JSON_DUMPER_TYPE_NONE) { jd_putc(dumper, ','); } print_newline_indent(dumper, dumper->current_depth); } /** * Common code to open an object/array/base64 value, printing * an opening character. * * It also makes various correctness checks. */ static gboolean json_dumper_begin_nested_element(json_dumper *dumper, enum json_dumper_element_type type) { if (!json_dumper_check_previous_error(dumper)) { return FALSE; } /* Make sure we won't overflow the dumper stack */ if (json_dumper_stack_would_overflow(dumper)) { return FALSE; } prepare_token(dumper); switch (type) { case JSON_DUMPER_TYPE_OBJECT: jd_putc(dumper, '{'); break; case JSON_DUMPER_TYPE_ARRAY: jd_putc(dumper, '['); break; case JSON_DUMPER_TYPE_BASE64: dumper->base64_state = 0; dumper->base64_save = 0; jd_putc(dumper, '"'); break; default: json_dumper_bad(dumper, "beginning unknown nested element type"); return FALSE; } dumper->state[dumper->current_depth] = type; /* * Guaranteed not to overflow, as json_dumper_stack_would_overflow() * returned FALSE. */ ++dumper->current_depth; dumper->state[dumper->current_depth] = JSON_DUMPER_TYPE_NONE; return TRUE; } /** * Common code to close an object/array/base64 value, printing a * closing character (and if necessary, it is preceded by newline * and indentation). * * It also makes various correctness checks. */ static gboolean json_dumper_end_nested_element(json_dumper *dumper, enum json_dumper_element_type type) { if (!json_dumper_check_previous_error(dumper)) { return FALSE; } guint8 prev_state = json_dumper_get_prev_state(dumper); switch (type) { case JSON_DUMPER_TYPE_OBJECT: if (JSON_DUMPER_TYPE(prev_state) != JSON_DUMPER_TYPE_OBJECT) { json_dumper_bad(dumper, "ending non-object nested item type as object"); return FALSE; } break; case JSON_DUMPER_TYPE_ARRAY: if (JSON_DUMPER_TYPE(prev_state) != JSON_DUMPER_TYPE_ARRAY) { json_dumper_bad(dumper, "ending non-array nested item type as array"); return FALSE; } break; case JSON_DUMPER_TYPE_BASE64: if (JSON_DUMPER_TYPE(prev_state) != JSON_DUMPER_TYPE_BASE64) { json_dumper_bad(dumper, "ending non-base64 nested item type as base64"); return FALSE; } break; default: json_dumper_bad(dumper, "ending unknown nested element type"); return FALSE; } if (prev_state & JSON_DUMPER_HAS_NAME) { json_dumper_bad(dumper, "finishing object with last item having name but no value"); return FALSE; } /* Make sure we won't underflow the dumper stack */ if (json_dumper_stack_would_underflow(dumper)) { return FALSE; } switch (type) { case JSON_DUMPER_TYPE_OBJECT: jd_putc(dumper, '}'); break; case JSON_DUMPER_TYPE_ARRAY: jd_putc(dumper, ']'); break; case JSON_DUMPER_TYPE_BASE64: { gchar buf[4]; gsize wrote; wrote = g_base64_encode_close(FALSE, buf, &dumper->base64_state, &dumper->base64_save); jd_puts_len(dumper, buf, wrote); jd_putc(dumper, '"'); break; } default: json_dumper_bad(dumper, "endning unknown nested element type"); return FALSE; } /* * Guaranteed not to underflow, as json_dumper_stack_would_underflow() * returned FALSE. */ --dumper->current_depth; return TRUE; } void json_dumper_begin_object(json_dumper *dumper) { json_dumper_begin_nested_element(dumper, JSON_DUMPER_TYPE_OBJECT); } void json_dumper_set_member_name(json_dumper *dumper, const char *name) { if (!json_dumper_check_previous_error(dumper)) { return; } guint8 prev_state = json_dumper_get_prev_state(dumper); /* Only object members, not array members, have names. */ if (JSON_DUMPER_TYPE(prev_state) != JSON_DUMPER_TYPE_OBJECT) { json_dumper_bad(dumper, "setting name on non-object nested item type"); return; } /* An object member name can only be set once before its value is set. */ if (prev_state & JSON_DUMPER_HAS_NAME) { json_dumper_bad(dumper, "setting name twice on an object member"); return; } prepare_token(dumper); json_puts_string(dumper, name, dumper->flags & JSON_DUMPER_DOT_TO_UNDERSCORE); jd_putc(dumper, ':'); if ((dumper->flags & JSON_DUMPER_FLAGS_PRETTY_PRINT)) { jd_putc(dumper, ' '); } dumper->state[dumper->current_depth - 1] |= JSON_DUMPER_HAS_NAME; } void json_dumper_end_object(json_dumper *dumper) { json_dumper_end_nested_element(dumper, JSON_DUMPER_TYPE_OBJECT); } void json_dumper_begin_array(json_dumper *dumper) { json_dumper_begin_nested_element(dumper, JSON_DUMPER_TYPE_ARRAY); } void json_dumper_end_array(json_dumper *dumper) { json_dumper_end_nested_element(dumper, JSON_DUMPER_TYPE_ARRAY); } static gboolean json_dumper_setting_value_ok(json_dumper *dumper) { guint8 prev_state = json_dumper_get_prev_state(dumper); switch (JSON_DUMPER_TYPE(prev_state)) { case JSON_DUMPER_TYPE_OBJECT: /* * This value is part of an object. As such, it must * have a name. */ if (!(prev_state & JSON_DUMPER_HAS_NAME)) { json_dumper_bad(dumper, "setting value of object member without a name"); return FALSE; } break; case JSON_DUMPER_TYPE_ARRAY: /* * This value is part of an array. As such, it's not * required to have a name (and shouldn't have a name; * that's already been checked in json_dumper_set_member_name()). */ break; case JSON_DUMPER_TYPE_BASE64: /* * We're in the middle of constructing a base64-encoded * value. Only json_dumper_write_base64() can be used * for that; we can't add individual values to it. */ json_dumper_bad(dumper, "attempt to set value of base64 item to something not base64-encoded"); return FALSE; case JSON_DUMPER_TYPE_NONE: case JSON_DUMPER_TYPE_VALUE: { guint8 curr_state = json_dumper_get_curr_state(dumper); switch (JSON_DUMPER_TYPE(curr_state)) { case JSON_DUMPER_TYPE_NONE: /* * We haven't put a value yet, so we can put one now. */ break; case JSON_DUMPER_TYPE_VALUE: /* * This value isn't part of an object or array, * and we've already put one value. */ json_dumper_bad(dumper, "value not in object or array immediately follows another value"); return FALSE; case JSON_DUMPER_TYPE_OBJECT: case JSON_DUMPER_TYPE_ARRAY: case JSON_DUMPER_TYPE_BASE64: /* * This should never be the case, no matter what * our callers do: * * JSON_DUMPER_TYPE_OBJECT can be the previous * type, meaning we're in the process of adding * elements to an object, but it should never be * the current type; * * JSON_DUMPER_TYPE_ARRAY can be the previous * type, meaning we're in the process of adding * elements to an array, but it should never be * the current type; * * JSON_DUMPER_TYPE_BASE64 should only be the * current type if we're in the middle of * building a base64 value, in which case the * previous type should also be JSON_DUMPER_TYPE_BASE64, * but that's not the previous type. */ json_dumper_bad(dumper, "internal error setting value - should not happen"); return FALSE; default: json_dumper_bad(dumper, "internal error setting value, bad current state - should not happen"); return FALSE; } break; } default: json_dumper_bad(dumper, "internal error setting value, bad previous state - should not happen"); return FALSE; } return TRUE; } void json_dumper_value_string(json_dumper *dumper, const char *value) { if (!json_dumper_check_previous_error(dumper)) { return; } if (!json_dumper_setting_value_ok(dumper)) { return; } prepare_token(dumper); json_puts_string(dumper, value, FALSE); dumper->state[dumper->current_depth] = JSON_DUMPER_TYPE_VALUE; } void json_dumper_value_double(json_dumper *dumper, double value) { if (!json_dumper_check_previous_error(dumper)) { return; } if (!json_dumper_setting_value_ok(dumper)) { return; } prepare_token(dumper); gchar buffer[G_ASCII_DTOSTR_BUF_SIZE] = { 0 }; if (isfinite(value) && g_ascii_dtostr(buffer, G_ASCII_DTOSTR_BUF_SIZE, value) && buffer[0]) { jd_puts(dumper, buffer); } else { jd_puts(dumper, "null"); } dumper->state[dumper->current_depth] = JSON_DUMPER_TYPE_VALUE; } void json_dumper_value_va_list(json_dumper *dumper, const char *format, va_list ap) { if (!json_dumper_check_previous_error(dumper)) { return; } if (!json_dumper_setting_value_ok(dumper)) { return; } prepare_token(dumper); jd_vprintf(dumper, format, ap); dumper->state[dumper->current_depth] = JSON_DUMPER_TYPE_VALUE; } void json_dumper_value_anyf(json_dumper *dumper, const char *format, ...) { va_list ap; va_start(ap, format); json_dumper_value_va_list(dumper, format, ap); va_end(ap); } gboolean json_dumper_finish(json_dumper *dumper) { if (!json_dumper_check_previous_error(dumper)) { return FALSE; } if (dumper->current_depth != 0) { json_dumper_bad(dumper, "JSON dumper stack not empty at finish"); return FALSE; } jd_putc(dumper, '\n'); dumper->state[0] = JSON_DUMPER_TYPE_NONE; return TRUE; } void json_dumper_begin_base64(json_dumper *dumper) { json_dumper_begin_nested_element(dumper, JSON_DUMPER_TYPE_BASE64); } void json_dumper_write_base64(json_dumper* dumper, const guchar *data, size_t len) { if (!json_dumper_check_previous_error(dumper)) { return; } guint8 prev_state = json_dumper_get_prev_state(dumper); if (JSON_DUMPER_TYPE(prev_state) != JSON_DUMPER_TYPE_BASE64) { json_dumper_bad(dumper, "writing base64 data to a non-base64 value"); return; } #define CHUNK_SIZE 1024 gchar buf[(CHUNK_SIZE / 3 + 1) * 4 + 4]; while (len > 0) { gsize chunk_size = len < CHUNK_SIZE ? len : CHUNK_SIZE; gsize output_size = g_base64_encode_step(data, chunk_size, FALSE, buf, &dumper->base64_state, &dumper->base64_save); jd_puts_len(dumper, buf, output_size); data += chunk_size; len -= chunk_size; } dumper->state[dumper->current_depth] = JSON_DUMPER_TYPE_BASE64; } void json_dumper_end_base64(json_dumper *dumper) { json_dumper_end_nested_element(dumper, JSON_DUMPER_TYPE_BASE64); }
C/C++
wireshark/wsutil/json_dumper.h
/** @file * Routines for serializing data as JSON. * * Copyright 2018, Peter Wu <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __JSON_DUMPER_H__ #define __JSON_DUMPER_H__ #include "ws_symbol_export.h" #include <glib.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif /** * Example: * * json_dumper dumper = { * .output_file = stdout, // or .output_string = g_string_new(NULL) * .flags = JSON_DUMPER_FLAGS_PRETTY_PRINT, * }; * json_dumper_begin_object(&dumper); * json_dumper_set_member_name(&dumper, "key"); * json_dumper_value_string(&dumper, "value"); * json_dumper_set_member_name(&dumper, "array"); * json_dumper_begin_array(&dumper); * json_dumper_value_anyf(&dumper, "true"); * json_dumper_value_double(&dumper, 1.0); * json_dumper_begin_base64(&dumper); * json_dumper_write_base64(&dumper, (const guchar *)"abcd", 4); * json_dumper_write_base64(&dumper, (const guchar *)"1234", 4); * json_dumper_end_base64(&dumper); * json_dumper_begin_object(&dumper); * json_dumper_end_object(&dumper); * json_dumper_begin_array(&dumper); * json_dumper_end_array(&dumper); * json_dumper_end_array(&dumper); * json_dumper_end_object(&dumper); * json_dumper_finish(&dumper); */ /** Maximum object/array nesting depth. */ #define JSON_DUMPER_MAX_DEPTH 1100 typedef struct json_dumper { FILE *output_file; /**< Output file. If it is not NULL, JSON will be dumped in the file. */ GString *output_string; /**< Output GLib strings. If it is not NULL, JSON will be dumped in the string. */ #define JSON_DUMPER_FLAGS_PRETTY_PRINT (1 << 0) /* Enable pretty printing. */ #define JSON_DUMPER_DOT_TO_UNDERSCORE (1 << 1) /* Convert dots to underscores in keys */ #define JSON_DUMPER_FLAGS_NO_DEBUG (1 << 17) /* Disable fatal ws_error messsges on error(intended for speeding up fuzzing). */ int flags; /* for internal use, initialize with zeroes. */ guint current_depth; gint base64_state; gint base64_save; guint8 state[JSON_DUMPER_MAX_DEPTH]; } json_dumper; WS_DLL_PUBLIC void json_dumper_begin_object(json_dumper *dumper); WS_DLL_PUBLIC void json_dumper_set_member_name(json_dumper *dumper, const char *name); WS_DLL_PUBLIC void json_dumper_end_object(json_dumper *dumper); WS_DLL_PUBLIC void json_dumper_begin_array(json_dumper *dumper); WS_DLL_PUBLIC void json_dumper_end_array(json_dumper *dumper); WS_DLL_PUBLIC void json_dumper_value_string(json_dumper *dumper, const char *value); WS_DLL_PUBLIC void json_dumper_value_double(json_dumper *dumper, double value); /** * Dump number, "true", "false" or "null" values. */ WS_DLL_PUBLIC void json_dumper_value_anyf(json_dumper *dumper, const char *format, ...) G_GNUC_PRINTF(2, 3); /** * Dump literal values (like json_dumper_value_anyf), but taking a va_list * as parameter. String values MUST be properly quoted by the caller, no * escaping occurs. Do not use with untrusted data. */ WS_DLL_PUBLIC void json_dumper_value_va_list(json_dumper *dumper, const char *format, va_list ap); WS_DLL_PUBLIC void json_dumper_begin_base64(json_dumper *dumper); WS_DLL_PUBLIC void json_dumper_end_base64(json_dumper *dumper); WS_DLL_PUBLIC void json_dumper_write_base64(json_dumper *dumper, const guchar *data, size_t len); /** * Finishes dumping data. Returns TRUE if everything is okay and FALSE if * something went wrong (open/close mismatch, missing values, etc.). */ WS_DLL_PUBLIC gboolean json_dumper_finish(json_dumper *dumper); #ifdef __cplusplus } #endif #endif /* __JSON_DUMPER_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C
wireshark/wsutil/mpeg-audio.c
/* mpeg-audio.c * * MPEG Audio header dissection * Written by Shaun Jackman <[email protected]> * Copyright 2007 Shaun Jackman * * Wiretap Library * SPDX-License-Identifier: GPL-2.0-or-later */ #include "mpeg-audio.h" static const int mpa_versions[4] = { 2, -1, 1, 0 }; static const int mpa_layers[4] = { -1, 2, 1, 0 }; static const unsigned int mpa_samples_data[3][3] = { { 384, 1152, 1152 }, { 384, 1152, 576 }, { 384, 1152, 576 }, }; static const unsigned int mpa_bitrates[3][3][16] = { /* kb/s */ { { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 }, { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 }, { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 }, }, { { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, }, { { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, }, }; static const unsigned int mpa_frequencies[3][4] = { { 44100, 48000, 32000 }, { 22050, 24000, 16000 }, { 11025, 12000, 8000 }, }; static const unsigned int mpa_padding_data[3] = { 4, 1, 1 }; int mpa_version(const struct mpa *mpa) { return mpa_versions[mpa->version]; } int mpa_layer(const struct mpa *mpa) { return mpa_layers[mpa->layer]; } unsigned mpa_samples(const struct mpa *mpa) { return mpa_samples_data[mpa_versions[mpa->version]][mpa_layer(mpa)]; } unsigned mpa_bitrate(const struct mpa *mpa) { return (1000 * (mpa_bitrates[mpa_versions[mpa->version]][mpa_layers[mpa->layer]][mpa->bitrate])); } unsigned mpa_frequency(const struct mpa *mpa) { return(mpa_frequencies[mpa_versions[mpa->version]][mpa->frequency]); } unsigned mpa_padding(const struct mpa *mpa) { return(mpa->padding ? mpa_padding_data[mpa_layers[mpa->layer]] : 0); } /* Decode an ID3v2 synchsafe integer. * See https://id3.org/id3v2.4.0-structure section 6.2. */ guint32 decode_synchsafe_int(guint32 input) { guint32 value; /* High-order byte */ value = (input >> 24) & 0x7f; /* Shift the result left to make room for the next 7 bits */ value <<= 7; /* Now OR in the 2nd byte */ value |= (input >> 16) & 0x7f; value <<= 7; /* ... and the 3rd */ value |= (input >> 8) & 0x7f; value <<= 7; /* For the 4th byte don't do the shift */ value |= input & 0x7f; return value; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/mpeg-audio.h
/** @file * * MPEG Audio header dissection * Written by Shaun Jackman <[email protected]> * Copyright 2007 Shaun Jackman * * Wiretap Library * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef MPA_H #define MPA_H 1 #include <glib.h> #include "ws_symbol_export.h" struct mpa { unsigned int emphasis :2; unsigned int original :1; unsigned int copyright :1; unsigned int modeext :2; unsigned int mode :2; unsigned int priv :1; unsigned int padding :1; unsigned int frequency :2; unsigned int bitrate :4; unsigned int protection :1; unsigned int layer :2; unsigned int version :2; unsigned int sync :11; }; #define MPA_UNMARSHAL_SYNC(n) ((n) >> 21 & 0x7ff) #define MPA_UNMARSHAL_VERSION(n) ((n) >> 19 & 0x3) #define MPA_UNMARSHAL_LAYER(n) ((n) >> 17 & 0x3) #define MPA_UNMARSHAL_PROTECTION(n) ((n) >> 16 & 0x1) #define MPA_UNMARSHAL_BITRATE(n) ((n) >> 12 & 0xf) #define MPA_UNMARSHAL_FREQUENCY(n) ((n) >> 10 & 0x3) #define MPA_UNMARSHAL_PADDING(n) ((n) >> 9 & 0x1) #define MPA_UNMARSHAL_PRIVATE(n) ((n) >> 8 & 0x1) #define MPA_UNMARSHAL_MODE(n) ((n) >> 6 & 0x3) #define MPA_UNMARSHAL_MODEEXT(n) ((n) >> 4 & 0x3) #define MPA_UNMARSHAL_COPYRIGHT(n) ((n) >> 3 & 0x1) #define MPA_UNMARSHAL_ORIGINAL(n) ((n) >> 2 & 0x1) #define MPA_UNMARSHAL_EMPHASIS(n) ((n) >> 0 & 0x3) #define MPA_UNMARSHAL(mpa, n) do { \ (mpa)->sync = MPA_UNMARSHAL_SYNC(n); \ (mpa)->version = MPA_UNMARSHAL_VERSION(n); \ (mpa)->layer = MPA_UNMARSHAL_LAYER(n); \ (mpa)->protection = MPA_UNMARSHAL_PROTECTION(n); \ (mpa)->bitrate = MPA_UNMARSHAL_BITRATE(n); \ (mpa)->frequency = MPA_UNMARSHAL_FREQUENCY(n); \ (mpa)->padding = MPA_UNMARSHAL_PADDING(n); \ (mpa)->priv = MPA_UNMARSHAL_PRIVATE(n); \ (mpa)->mode = MPA_UNMARSHAL_MODE(n); \ (mpa)->modeext = MPA_UNMARSHAL_MODEEXT(n); \ (mpa)->copyright = MPA_UNMARSHAL_COPYRIGHT(n); \ (mpa)->original = MPA_UNMARSHAL_ORIGINAL(n); \ (mpa)->emphasis = MPA_UNMARSHAL_EMPHASIS(n); \ } while (0) WS_DLL_PUBLIC int mpa_version(const struct mpa *); WS_DLL_PUBLIC int mpa_layer(const struct mpa *); WS_DLL_PUBLIC unsigned int mpa_samples(const struct mpa *); WS_DLL_PUBLIC unsigned int mpa_bitrate(const struct mpa *); WS_DLL_PUBLIC unsigned int mpa_frequency(const struct mpa *); WS_DLL_PUBLIC unsigned int mpa_padding(const struct mpa *); WS_DLL_PUBLIC guint32 decode_synchsafe_int(guint32); #define MPA_DATA_BYTES(mpa) (mpa_bitrate(mpa) * mpa_samples(mpa) \ / mpa_frequency(mpa) / 8) #define MPA_BYTES(mpa) (MPA_DATA_BYTES(mpa) + mpa_padding(mpa)) #define MPA_DURATION_NS(mpa) \ (1000000000 / mpa_frequency(mpa) * mpa_samples(mpa)) enum { MPA_SYNC = 0x7ff }; #define MPA_SYNC_VALID(mpa) ((mpa)->sync == MPA_SYNC) #define MPA_VERSION_VALID(mpa) (mpa_version(mpa) >= 0) #define MPA_LAYER_VALID(mpa) (mpa_layer(mpa) >= 0) #define MPA_BITRATE_VALID(mpa) (mpa_bitrate(mpa) > 0) #define MPA_FREQUENCY_VALID(mpa) (mpa_frequency(mpa) > 0) #define MPA_VALID(mpa) (MPA_SYNC_VALID(mpa) \ && MPA_VERSION_VALID(mpa) && MPA_LAYER_VALID(mpa) \ && MPA_BITRATE_VALID(mpa) && MPA_FREQUENCY_VALID(mpa)) #endif
C
wireshark/wsutil/nstime.c
/* nstime.c * Routines for manipulating nstime_t structures * * Copyright (c) 2005 MX Telecom Ltd. <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "nstime.h" #include <stdio.h> #include <string.h> #include "epochs.h" #include "time_util.h" #include "to_str.h" /* this is #defined so that we can clearly see that we have the right number of zeros, rather than as a guard against the number of nanoseconds in a second changing ;) */ #define NS_PER_S 1000000000 /* set the given nstime_t to zero */ void nstime_set_zero(nstime_t *nstime) { nstime->secs = 0; nstime->nsecs = 0; } /* is the given nstime_t currently zero? */ gboolean nstime_is_zero(const nstime_t *nstime) { return nstime->secs == 0 && nstime->nsecs == 0; } /* set the given nstime_t to (0,maxint) to mark it as "unset" * That way we can find the first frame even when a timestamp * is zero (fix for bug 1056) */ void nstime_set_unset(nstime_t *nstime) { nstime->secs = 0; nstime->nsecs = G_MAXINT; } /* is the given nstime_t currently (0,maxint)? */ gboolean nstime_is_unset(const nstime_t *nstime) { if(nstime->secs == 0 && nstime->nsecs == G_MAXINT) { return TRUE; } else { return FALSE; } } /** function: nstime_copy * * a = b */ void nstime_copy(nstime_t *a, const nstime_t *b) { a->secs = b->secs; a->nsecs = b->nsecs; } /* * function: nstime_delta * delta = b - a */ void nstime_delta(nstime_t *delta, const nstime_t *b, const nstime_t *a ) { if (b->secs == a->secs) { /* The seconds part of b is the same as the seconds part of a, so if the nanoseconds part of the first time is less than the nanoseconds part of a, b is before a. The nanoseconds part of the delta should just be the difference between the nanoseconds part of b and the nanoseconds part of a; don't adjust the seconds part of the delta, as it's OK if the nanoseconds part is negative, and an overflow can never result. */ delta->secs = 0; delta->nsecs = b->nsecs - a->nsecs; } else if (b->secs < a->secs) { /* The seconds part of b is less than the seconds part of a, so b is before a. Both the "seconds" and "nanoseconds" value of the delta should have the same sign, so if the difference between the nanoseconds values would be *positive*, subtract 1,000,000,000 from it, and add one to the seconds value. */ delta->secs = b->secs - a->secs; delta->nsecs = b->nsecs - a->nsecs; if(delta->nsecs > 0) { delta->nsecs -= NS_PER_S; delta->secs ++; } } else { delta->secs = b->secs - a->secs; delta->nsecs = b->nsecs - a->nsecs; if(delta->nsecs < 0) { delta->nsecs += NS_PER_S; delta->secs --; } } } /* * function: nstime_sum * sum = a + b */ void nstime_sum(nstime_t *sum, const nstime_t *a, const nstime_t *b) { sum->secs = a->secs + b->secs; sum->nsecs = a->nsecs + b->nsecs; if(sum->nsecs>=NS_PER_S || (sum->nsecs>0 && sum->secs<0)){ sum->nsecs-=NS_PER_S; sum->secs++; } else if(sum->nsecs<=-NS_PER_S || (sum->nsecs<0 && sum->secs>0)) { sum->nsecs+=NS_PER_S; sum->secs--; } } /* * function: nstime_cmp * * a > b : > 0 * a = b : 0 * a < b : < 0 */ int nstime_cmp (const nstime_t *a, const nstime_t *b ) { if (G_UNLIKELY(nstime_is_unset(a))) { if (G_UNLIKELY(nstime_is_unset(b))) { return 0; /* "no time stamp" is "equal" to "no time stamp" */ } else { return -1; /* and is less than all time stamps */ } } else { if (G_UNLIKELY(nstime_is_unset(b))) { return 1; } } if (a->secs == b->secs) { return a->nsecs - b->nsecs; } else { return (int) (a->secs - b->secs); } } guint nstime_hash(const nstime_t *nstime) { gint64 val1 = (gint64)nstime->secs; return g_int64_hash(&val1) ^ g_int_hash(&nstime->nsecs); } /* * function: nstime_to_msec * converts nstime to double, time base is milli seconds */ double nstime_to_msec(const nstime_t *nstime) { return ((double)nstime->secs*1000 + (double)nstime->nsecs/1000000); } /* * function: nstime_to_sec * converts nstime to double, time base is seconds */ double nstime_to_sec(const nstime_t *nstime) { return ((double)nstime->secs + (double)nstime->nsecs/NS_PER_S); } /* * This code is based on the Samba code: * * Unix SMB/Netbios implementation. * Version 1.9. * time handling functions * Copyright (C) Andrew Tridgell 1992-1998 */ #ifndef TIME_T_MIN #define TIME_T_MIN ((time_t) ((time_t)0 < (time_t) -1 ? (time_t) 0 \ : (time_t) (~0ULL << (sizeof (time_t) * CHAR_BIT - 1)))) #endif #ifndef TIME_T_MAX #define TIME_T_MAX ((time_t) (~ (time_t) 0 - TIME_T_MIN)) #endif static gboolean common_filetime_to_nstime(nstime_t *nstime, guint64 ftsecs, int nsecs) { gint64 secs; /* * Shift the seconds from the Windows epoch to the UN*X epoch. * ftsecs's value should fit in a 64-bit signed variable, as * ftsecs is derived from a 64-bit fractions-of-a-second value, * and is far from the maximum 64-bit signed value, and * EPOCH_DELTA_1601_01_01_00_00_00_UTC is also far from the * maximum 64-bit signed value, so the difference between them * should also fit in a 64-bit signed value. */ secs = (gint64)ftsecs - EPOCH_DELTA_1601_01_01_00_00_00_UTC; if (!(TIME_T_MIN <= secs && secs <= TIME_T_MAX)) { /* The result won't fit in a time_t */ return FALSE; } /* * Get the time as seconds and nanoseconds. */ nstime->secs = (time_t) secs; nstime->nsecs = nsecs; return TRUE; } /* * function: filetime_to_nstime * converts a Windows FILETIME value to an nstime_t * returns TRUE if the conversion succeeds, FALSE if it doesn't * (for example, with a 32-bit time_t, the time overflows or * underflows time_t) */ gboolean filetime_to_nstime(nstime_t *nstime, guint64 filetime) { guint64 ftsecs; int nsecs; /* * Split into seconds and tenths of microseconds, and * then convert tenths of microseconds to nanoseconds. */ ftsecs = filetime / 10000000; nsecs = (int)((filetime % 10000000)*100); return common_filetime_to_nstime(nstime, ftsecs, nsecs); } /* * function: nsfiletime_to_nstime * converts a Windows FILETIME-like value, but given in nanoseconds * rather than 10ths of microseconds, to an nstime_t * returns TRUE if the conversion succeeds, FALSE if it doesn't * (for example, with a 32-bit time_t, the time overflows or * underflows time_t) */ gboolean nsfiletime_to_nstime(nstime_t *nstime, guint64 nsfiletime) { guint64 ftsecs; int nsecs; /* Split into seconds and nanoseconds. */ ftsecs = nsfiletime / NS_PER_S; nsecs = (int)(nsfiletime % NS_PER_S); return common_filetime_to_nstime(nstime, ftsecs, nsecs); } /* * function: iso8601_to_nstime * parses a character string for a date and time given in * ISO 8601 date-time format (eg: 2014-04-07T05:41:56.782+00:00) * and converts to an nstime_t * returns number of chars parsed on success, or 0 on failure * * NB. ISO 8601 is actually a lot more flexible than the above format, * much to a developer's chagrin. The "basic format" is distinguished from * the "extended format" by lacking the - and : separators. This function * supports both the basic and extended format (as well as both simultaneously) * with several common options and extensions. Time resolution is supported * up to nanoseconds (9 fractional digits) or down to whole minutes (omitting * the seconds component in the latter case). The T separator can be replaced * by a space in either format (a common extension not in ISO 8601 but found * in, e.g., RFC 3339) or omitted entirely in the basic format. * * Many standards that use ISO 8601 implement profiles with additional * constraints, such as requiring that the seconds field be present, only * allowing "." as the decimal separator, or limiting the number of fractional * digits. Callers that wish to check constraints not yet enforced by a * profile supported by the function must do so themselves. * * Future improvements could parse other ISO 8601 formats, such as * YYYY-Www-D, YYYY-DDD, etc. For a relatively easy introduction to * these formats, see wikipedia: https://en.wikipedia.org/wiki/ISO_8601 */ guint8 iso8601_to_nstime(nstime_t *nstime, const char *ptr, iso8601_fmt_e format) { struct tm tm; gint n_scanned = 0; gint n_chars = 0; guint frac = 0; gint off_hr = 0; gint off_min = 0; guint8 ret_val = 0; const char *start = ptr; char sign = '\0'; gboolean has_separator = FALSE; gboolean have_offset = FALSE; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; nstime_set_unset(nstime); /* Verify that we start with a four digit year and then look for the * separator. */ for (n_scanned = 0; n_scanned < 4; n_scanned++) { if (!g_ascii_isdigit(*ptr)) { return 0; } tm.tm_year *= 10; tm.tm_year += *ptr++ - '0'; } if (*ptr == '-') { switch (format) { case ISO8601_DATETIME_BASIC: return 0; case ISO8601_DATETIME: case ISO8601_DATETIME_AUTO: default: has_separator = TRUE; ptr++; }; } else if (g_ascii_isdigit(*ptr)) { switch (format) { case ISO8601_DATETIME: return 0; case ISO8601_DATETIME_BASIC: case ISO8601_DATETIME_AUTO: default: has_separator = FALSE; }; } else { return 0; } tm.tm_year -= 1900; /* struct tm expects number of years since 1900 */ /* Note: sscanf is known to be inconsistent across platforms with respect to whether a %n is counted as a return value or not (XXX: Is this still true, despite the express comments of C99 ยง7.19.6.2 12?), so we use '<'/'>=' */ /* XXX: sscanf allows an optional sign indicator before each integer * converted (whether with %d or %u), so this will convert some bogus * strings. Either checking afterwards or doing the whole thing by hand * as with the year above is the only correct way. (strptime certainly * can't handle the basic format.) */ n_scanned = sscanf(ptr, has_separator ? "%2u-%2u%n" : "%2u%2u%n", &tm.tm_mon, &tm.tm_mday, &n_chars); if (n_scanned >= 2) { /* Got year, month, and day */ tm.tm_mon--; /* struct tm expects 0-based month */ ptr += n_chars; } else { return 0; } if (*ptr == 'T' || *ptr == ' ') { /* The 'T' between date and time is optional if the meaning is unambiguous. We also allow for ' ' here per RFC 3339 to support formats such as editcap's -A/-B options. */ ptr++; } else if (has_separator) { /* Allow no separator between date and time iff we have no separator between units. (Some extended formats may negotiate no separator here, so this could be changed.) */ return 0; } /* Now we're on to the time part. We'll require a minimum of hours and minutes. */ n_scanned = sscanf(ptr, has_separator ? "%2u:%2u%n" : "%2u%2u%n", &tm.tm_hour, &tm.tm_min, &n_chars); if (n_scanned >= 2) { ptr += n_chars; } else { /* didn't get hours and minutes */ return 0; } /* Test for (whole) seconds */ if ((has_separator && *ptr == ':') || (!has_separator && g_ascii_isdigit(*ptr))) { /* Looks like we should have them */ if (1 > sscanf(ptr, has_separator ? ":%2u%n" : "%2u%n", &tm.tm_sec, &n_chars)) { /* Couldn't get them */ return 0; } ptr += n_chars; /* Now let's test for fractional seconds */ if (*ptr == '.' || *ptr == ',') { /* Get fractional seconds */ ptr++; if (1 <= sscanf(ptr, "%u%n", &frac, &n_chars)) { /* normalize frac to nanoseconds */ if ((frac >= 1000000000) || (frac == 0)) { frac = 0; } else { switch (n_chars) { /* including leading zeros */ case 1: frac *= 100000000; break; case 2: frac *= 10000000; break; case 3: frac *= 1000000; break; case 4: frac *= 100000; break; case 5: frac *= 10000; break; case 6: frac *= 1000; break; case 7: frac *= 100; break; case 8: frac *= 10; break; default: break; } } ptr += n_chars; } /* If we didn't get frac, it's still its default of 0 */ } } else { /* No seconds. ISO 8601 allows decimal fractions of a minute here, * but that's pretty rare in practice. Could be added later if needed. */ tm.tm_sec = 0; } /* Validate what we got so far. mktime() doesn't care about strange values but we should at least start with something valid */ if (!tm_is_valid(&tm)) { return 0; } /* Check for a time zone offset */ if (*ptr == '-' || *ptr == '+' || *ptr == 'Z') { /* Just in case somewhere decides to observe a timezone of -00:30 or * some such. */ sign = *ptr; /* We have a UTC-relative offset */ if (*ptr == 'Z') { off_hr = off_min = 0; have_offset = TRUE; ptr++; } else { off_hr = off_min = 0; n_scanned = sscanf(ptr, "%3d%n", &off_hr, &n_chars); if (n_scanned >= 1) { /* Definitely got hours */ have_offset = TRUE; ptr += n_chars; n_scanned = sscanf(ptr, *ptr == ':' ? ":%2d%n" : "%2d%n", &off_min, &n_chars); if (n_scanned >= 1) { /* Got minutes too */ ptr += n_chars; } } else { /* Didn't get a valid offset, treat as if there's none at all */ have_offset = FALSE; } } } if (have_offset) { nstime->secs = mktime_utc(&tm); if (sign == '+') { nstime->secs -= (off_hr * 3600) + (off_min * 60); } else if (sign == '-') { /* -00:00 is illegal according to ISO 8601, but RFC 3339 allows * it under a convention where -00:00 means "time in UTC is known, * local timezone is unknown." This has the same value as an * offset of Z or +00:00, but semantically implies that UTC is * not the preferred time zone, which is immaterial to us. */ /* Add the time, but reverse the sign of off_hr, which includes * the negative sign. */ nstime->secs += ((-off_hr) * 3600) + (off_min * 60); } } else { /* No UTC offset given; ISO 8601 says this means local time */ nstime->secs = mktime(&tm); } nstime->nsecs = frac; ret_val = (guint)(ptr-start); return ret_val; } /* * function: unix_epoch_to_nstime * parses a character string for a date and time given in * a floating point number containing a Unix epoch date-time * format (e.g. 1600000000.000 for Sun Sep 13 05:26:40 AM PDT 2020) * and converts to an nstime_t * returns number of chars parsed on success, or 0 on failure * * Reference: https://en.wikipedia.org/wiki/Unix_time */ guint8 unix_epoch_to_nstime(nstime_t *nstime, const char *ptr) { struct tm tm; char *ptr_new; gint n_chars = 0; guint frac = 0; guint8 ret_val = 0; const char *start = ptr; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; nstime_set_unset(nstime); if (!(ptr_new = ws_strptime(ptr, "%s", &tm))) { return 0; } /* No UTC offset given; ISO 8601 says this means local time */ nstime->secs = mktime(&tm); /* Now let's test for fractional seconds */ if (*ptr_new == '.' || *ptr_new == ',') { /* Get fractional seconds */ ptr_new++; if (1 <= sscanf(ptr_new, "%u%n", &frac, &n_chars)) { /* normalize frac to nanoseconds */ if ((frac >= 1000000000) || (frac == 0)) { frac = 0; } else { switch (n_chars) { /* including leading zeros */ case 1: frac *= 100000000; break; case 2: frac *= 10000000; break; case 3: frac *= 1000000; break; case 4: frac *= 100000; break; case 5: frac *= 10000; break; case 6: frac *= 1000; break; case 7: frac *= 100; break; case 8: frac *= 10; break; default: break; } } ptr_new += n_chars; } /* If we didn't get frac, it's still its default of 0 */ } else { tm.tm_sec = 0; } nstime->nsecs = frac; /* return pointer shift */ ret_val = (guint)(ptr_new-start); return ret_val; } size_t nstime_to_iso8601(char *buf, size_t buf_size, const nstime_t *nstime) { struct tm *tm; #ifndef _WIN32 struct tm tm_time; #endif size_t len; #ifdef _WIN32 /* * Do not use gmtime_s(), as it will call and * exception handler if the time we're providing * is < 0, and that will, by default, exit. * ("Programmers not bothering to check return * values? Try new Microsoft Visual Studio, * with Parameter Validation(R)! Kill insufficiently * careful programs - *and* the processes running them - * fast!") * * We just want to report this as an unrepresentable * time. It fills in a per-thread structure, which * is sufficiently thread-safe for our purposes. */ tm = gmtime(&nstime->secs); #else /* * Use gmtime_r(), because the Single UNIX Specification * does *not* guarantee that gmtime() is thread-safe. * Perhaps it is on all platforms on which we run, but * this way we don't have to check. */ tm = gmtime_r(&nstime->secs, &tm_time); #endif if (tm == NULL) { return 0; } /* Some platforms (MinGW-w64) do not support %F or %T. */ /* Returns number of bytes, excluding terminaning null, placed in * buf, or zero if there is not enough space for the whole string. */ len = strftime(buf, buf_size, "%Y-%m-%dT%H:%M:%S", tm); if (len == 0) { return 0; } ws_assert(len < buf_size); buf += len; buf_size -= len; len += snprintf(buf, buf_size, ".%09dZ", nstime->nsecs); return len; } void nstime_to_unix(char *buf, size_t buf_size, const nstime_t *nstime) { display_signed_time(buf, buf_size, (gint64) nstime->secs, nstime->nsecs, WS_TSPREC_NSEC); } /* * 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: */
C/C++
wireshark/wsutil/nstime.h
/* nstime.h * Definition of data structure to hold time values with nanosecond resolution * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __NSTIME_H__ #define __NSTIME_H__ #include <wireshark.h> #include <time.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @file * Definition of data structure to hold time values with nanosecond resolution */ /** data structure to hold time values with nanosecond resolution*/ typedef struct { time_t secs; int nsecs; } nstime_t; /* Macros that expand to nstime_t initializers */ /* Initialize to zero */ #define NSTIME_INIT_ZERO {0, 0} /* Initialize to unset */ #define NSTIME_INIT_UNSET {0, G_MAXINT} /* Initialize to a specified number of seconds and nanoseconds */ #define NSTIME_INIT_SECS_NSECS(secs, nsecs) {secs, nsecs} /* Initialize to a specified number of seconds and microseconds */ #define NSTIME_INIT_SECS_USECS(secs, usecs) {secs, usecs*1000} /* Initialize to a specified number of seconds and milliseconds */ #define NSTIME_INIT_SECS_MSECS(secs, msecs) {secs, msecs*1000000} /* Initialize to a specified number of seconds */ #define NSTIME_INIT_SECS(secs) {secs, 0} /* Initialize to the maximum possible value */ #define NSTIME_INIT_MAX {sizeof(time_t) > sizeof(int) ? LONG_MAX : INT_MAX, INT_MAX} /* functions */ /** set the given nstime_t to zero */ WS_DLL_PUBLIC void nstime_set_zero(nstime_t *nstime); /** is the given nstime_t currently zero? */ WS_DLL_PUBLIC gboolean nstime_is_zero(const nstime_t *nstime); /** set the given nstime_t to (0,maxint) to mark it as "unset" * That way we can find the first frame even when a timestamp * is zero (fix for bug 1056) */ WS_DLL_PUBLIC void nstime_set_unset(nstime_t *nstime); /* is the given nstime_t currently (0,maxint)? */ WS_DLL_PUBLIC gboolean nstime_is_unset(const nstime_t *nstime); /** duplicate the current time * * a = b */ WS_DLL_PUBLIC void nstime_copy(nstime_t *a, const nstime_t *b); /** calculate the delta between two times (can be negative!) * * delta = b-a * * Note that it is acceptable for two or more of the arguments to point at the * same structure. */ WS_DLL_PUBLIC void nstime_delta(nstime_t *delta, const nstime_t *b, const nstime_t *a ); /** calculate the sum of two times * * sum = a+b * * Note that it is acceptable for two or more of the arguments to point at the * same structure. */ WS_DLL_PUBLIC void nstime_sum(nstime_t *sum, const nstime_t *a, const nstime_t *b ); /** sum += a */ #define nstime_add(sum, a) nstime_sum(sum, sum, a) /** sum -= a */ #define nstime_subtract(sum, a) nstime_delta(sum, sum, a) /** compare two times are return a value similar to memcmp() or strcmp(). * * a > b : > 0 * a = b : 0 * a < b : < 0 */ WS_DLL_PUBLIC int nstime_cmp (const nstime_t *a, const nstime_t *b ); WS_DLL_PUBLIC guint nstime_hash(const nstime_t *nstime); /** converts nstime to double, time base is milli seconds */ WS_DLL_PUBLIC double nstime_to_msec(const nstime_t *nstime); /** converts nstime to double, time base is seconds */ WS_DLL_PUBLIC double nstime_to_sec(const nstime_t *nstime); /** converts Windows FILETIME to nstime, returns TRUE on success, FALSE on failure */ WS_DLL_PUBLIC gboolean filetime_to_nstime(nstime_t *nstime, guint64 filetime); /** converts time like Windows FILETIME, but expressed in nanoseconds rather than tenths of microseconds, to nstime, returns TRUE on success, FALSE on failure */ WS_DLL_PUBLIC gboolean nsfiletime_to_nstime(nstime_t *nstime, guint64 nsfiletime); typedef enum { ISO8601_DATETIME, /** e.g. 2014-07-04T12:34:56.789+00:00 */ ISO8601_DATETIME_BASIC, /** ISO8601 Basic format, i.e. no - : separators */ ISO8601_DATETIME_AUTO, /** Autodetect the presence of separators */ } iso8601_fmt_e; /** parse an ISO 8601 format datetime string to nstime, returns number of chars parsed on success, 0 on failure. Note that nstime is set to unset in the case of failure */ WS_DLL_PUBLIC guint8 iso8601_to_nstime(nstime_t *nstime, const char *ptr, iso8601_fmt_e format); /** parse an Unix epoch timestamp format datetime string to nstime, returns number of chars parsed on success, 0 on failure. Note that nstime is set to unset in the case of failure */ WS_DLL_PUBLIC guint8 unix_epoch_to_nstime(nstime_t *nstime, const char *ptr); #define NSTIME_ISO8601_BUFSIZE sizeof("YYYY-MM-DDTHH:MM:SS.123456789Z") WS_DLL_PUBLIC size_t nstime_to_iso8601(char *buf, size_t buf_size, const nstime_t *nstime); /* 64 bit signed number plus nanosecond fractional part */ #define NSTIME_UNIX_BUFSIZE (20+10+1) WS_DLL_PUBLIC void nstime_to_unix(char *buf, size_t buf_size, const nstime_t *nstime); /* * Timestamp precision values. * * The value is the number of digits of precision after the integral part. */ typedef enum { WS_TSPREC_SEC = 0, WS_TSPREC_100_MSEC = 1, WS_TSPREC_10_MSEC = 2, WS_TSPREC_MSEC = 3, WS_TSPREC_USEC = 6, WS_TSPREC_NSEC = 9 } ws_tsprec_e; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __NSTIME_H__ */
C
wireshark/wsutil/os_version_info.c
/* os_version_info.c * Routines to report operating system version information * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <wsutil/os_version_info.h> #include <string.h> #include <errno.h> #ifdef HAVE_SYS_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_MACOS_FRAMEWORKS #include <CoreFoundation/CoreFoundation.h> #include <wsutil/cfutils.h> #endif #include <wsutil/unicode-utils.h> /* * Handles the rather elaborate process of getting OS version information * from macOS (we want the macOS version, not the Darwin version, the latter * being easy to get with uname()). */ #ifdef HAVE_MACOS_FRAMEWORKS /* * Fetch a string, as a UTF-8 C string, from a dictionary, given a key. */ static char * get_string_from_dictionary(CFPropertyListRef dict, CFStringRef key) { CFStringRef cfstring; cfstring = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)dict, (const void *)key); if (cfstring == NULL) return NULL; if (CFGetTypeID(cfstring) != CFStringGetTypeID()) { /* It isn't a string. Punt. */ return NULL; } return CFString_to_C_string(cfstring); } /* * Get the macOS version information, and append it to the GString. * Return TRUE if we succeed, FALSE if we fail. * * XXX - this gives the OS name as "Mac OS X" even if Apple called/calls * it "OS X" or "macOS". */ static gboolean get_macos_version_info(GString *str) { static const UInt8 server_version_plist_path[] = "/System/Library/CoreServices/ServerVersion.plist"; static const UInt8 system_version_plist_path[] = "/System/Library/CoreServices/SystemVersion.plist"; CFURLRef version_plist_file_url; CFReadStreamRef version_plist_stream; CFDictionaryRef version_dict; char *string; /* * On macOS, report the macOS version number as the OS, and put * the Darwin information in parentheses. * * Alas, Gestalt() is deprecated in Mountain Lion, so the build * fails if you treat deprecation warnings as fatal. I don't * know of any replacement API, so we fall back on reading * /System/Library/CoreServices/ServerVersion.plist if it * exists, otherwise /System/Library/CoreServices/SystemVersion.plist, * and using ProductUserVisibleVersion. We also get the build * version from ProductBuildVersion and the product name from * ProductName. */ version_plist_file_url = CFURLCreateFromFileSystemRepresentation(NULL, server_version_plist_path, sizeof server_version_plist_path - 1, false); if (version_plist_file_url == NULL) return FALSE; version_plist_stream = CFReadStreamCreateWithFile(NULL, version_plist_file_url); CFRelease(version_plist_file_url); if (version_plist_stream == NULL) return FALSE; if (!CFReadStreamOpen(version_plist_stream)) { CFRelease(version_plist_stream); /* * Try SystemVersion.plist. */ version_plist_file_url = CFURLCreateFromFileSystemRepresentation(NULL, system_version_plist_path, sizeof system_version_plist_path - 1, false); if (version_plist_file_url == NULL) return FALSE; version_plist_stream = CFReadStreamCreateWithFile(NULL, version_plist_file_url); CFRelease(version_plist_file_url); if (version_plist_stream == NULL) return FALSE; if (!CFReadStreamOpen(version_plist_stream)) { CFRelease(version_plist_stream); return FALSE; } } #ifdef HAVE_CFPROPERTYLISTCREATEWITHSTREAM version_dict = (CFDictionaryRef)CFPropertyListCreateWithStream(NULL, version_plist_stream, 0, kCFPropertyListImmutable, NULL, NULL); #else version_dict = (CFDictionaryRef)CFPropertyListCreateFromStream(NULL, version_plist_stream, 0, kCFPropertyListImmutable, NULL, NULL); #endif if (version_dict == NULL) { CFRelease(version_plist_stream); return FALSE; } if (CFGetTypeID(version_dict) != CFDictionaryGetTypeID()) { /* This is *supposed* to be a dictionary. Punt. */ CFRelease(version_dict); CFReadStreamClose(version_plist_stream); CFRelease(version_plist_stream); return FALSE; } /* Get the product name string. */ string = get_string_from_dictionary(version_dict, CFSTR("ProductName")); if (string == NULL) { CFRelease(version_dict); CFReadStreamClose(version_plist_stream); CFRelease(version_plist_stream); return FALSE; } g_string_append_printf(str, "%s", string); g_free(string); /* Get the OS version string. */ string = get_string_from_dictionary(version_dict, CFSTR("ProductUserVisibleVersion")); if (string == NULL) { CFRelease(version_dict); CFReadStreamClose(version_plist_stream); CFRelease(version_plist_stream); return FALSE; } g_string_append_printf(str, " %s", string); g_free(string); /* Get the build string */ string = get_string_from_dictionary(version_dict, CFSTR("ProductBuildVersion")); if (string == NULL) { CFRelease(version_dict); CFReadStreamClose(version_plist_stream); CFRelease(version_plist_stream); return FALSE; } g_string_append_printf(str, ", build %s", string); g_free(string); CFRelease(version_dict); CFReadStreamClose(version_plist_stream); CFRelease(version_plist_stream); return TRUE; } #endif #ifdef _WIN32 typedef LONG (WINAPI * RtlGetVersionProc) (OSVERSIONINFOEX *); #ifndef STATUS_SUCCESS #define STATUS_SUCCESS 0 #endif #include <stdlib.h> /* * Determine whether it's 32-bit or 64-bit Windows based on the * instruction set; this only tests for the instruction sets * that we currently support for Windows, it doesn't bother with MIPS, * PowerPC, Alpha, or IA-64, nor does it bother wieth 32-bit ARM. */ static void add_os_bitsize(GString *str, SYSTEM_INFO *system_info) { switch (system_info->wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: #ifdef PROCESSOR_ARCHITECTURE_ARM64 case PROCESSOR_ARCHITECTURE_ARM64: #endif g_string_append(str, "64-bit "); break; case PROCESSOR_ARCHITECTURE_INTEL: g_string_append(str, "32-bit "); break; default: break; } } /* * Test whether the OS an "NT Workstation" version, meaning "not server". */ static gboolean is_nt_workstation(OSVERSIONINFOEX *win_version_info) { return win_version_info->wProductType == VER_NT_WORKSTATION; } #endif // _WIN32 /* * Get the OS version, and append it to the GString */ void get_os_version_info(GString *str) { #if defined(_WIN32) OSVERSIONINFOEX win_version_info = {0}; RtlGetVersionProc RtlGetVersionP = 0; LONG version_status = STATUS_ENTRYPOINT_NOT_FOUND; // Any nonzero value should work. /* * We want the major and minor Windows version along with other * information. GetVersionEx provides this, but is deprecated. * We use RtlGetVersion instead, which requires a bit of extra * effort. */ HMODULE ntdll_module = LoadLibrary(_T("ntdll.dll")); if (ntdll_module) { DIAG_OFF(cast-function-type) RtlGetVersionP = (RtlGetVersionProc) GetProcAddress(ntdll_module, "RtlGetVersion"); DIAG_ON(cast-function-type) } if (RtlGetVersionP) { win_version_info.dwOSVersionInfoSize = sizeof(win_version_info); version_status = RtlGetVersionP(&win_version_info); } if (ntdll_module) { FreeLibrary(ntdll_module); } if (version_status != STATUS_SUCCESS) { /* * XXX - get the failure reason. */ g_string_append(str, "unknown Windows version"); return; } SYSTEM_INFO system_info; memset(&system_info, '\0', sizeof system_info); /* * Look for and use the GetNativeSystemInfo() function to get the * correct processor architecture even when running 32-bit Wireshark * in WOW64 (x86 emulation on 64-bit Windows). * * However, the documentation for GetNativeSystemInfo() says * * If the function is called from an x86 or x64 application * running on a 64-bit system that does not have an Intel64 * or x64 processor (such as ARM64), it will return information * as if the system is x86 only if x86 emulation is supported * (or x64 if x64 emulation is also supported). * * so it appears that it will *not* return the correct processor * architecture if running x86-64 Wireshark on ARM64 with * x86-64 emulation - it will presumably say "x86-64", not "ARM64". * * So we use it to say "32-bit" or "64-bit", but we don't use * it to say "N-bit x86" or "N-bit ARM". * * It Would Be Nice if there were some way to report that * Wireshark is running in emulation on an ARM64 system; * that might be important if, for example, a user is * reporting a capture problem, as there currently isn't * a version of Npcap that can support x86-64 programs on * an ARM64 system. */ GetNativeSystemInfo(&system_info); switch (win_version_info.dwPlatformId) { case VER_PLATFORM_WIN32s: /* Shyeah, right. */ g_string_append_printf(str, "Windows 3.1 with Win32s"); break; case VER_PLATFORM_WIN32_WINDOWS: /* * Windows OT. * * https://nsis-dev.github.io/NSIS-Forums/html/t-128527.html * * claims that * * HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion * * has a key ProductName, at least in Windows M3, the * value of that key appears to be an OS product name. */ switch (win_version_info.dwMajorVersion) { case 4: /* 3 cheers for Microsoft marketing! */ switch (win_version_info.dwMinorVersion) { case 0: g_string_append_printf(str, "Windows 95"); break; case 10: g_string_append_printf(str, "Windows 98"); break; case 90: g_string_append_printf(str, "Windows Me"); break; default: g_string_append_printf(str, "Windows OT, unknown version %lu.%lu", win_version_info.dwMajorVersion, win_version_info.dwMinorVersion); break; } break; default: g_string_append_printf(str, "Windows OT, unknown version %lu.%lu", win_version_info.dwMajorVersion, win_version_info.dwMinorVersion); break; } break; case VER_PLATFORM_WIN32_NT: /* * Windows NT. * * https://stackoverflow.com/a/19778234/16139739 * * claims that * * HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion * * has a key ProductName that is "present for Windows XP * and aboeve[sic]". The value of that key gives a * "product name"... * * ...at least until Windows 11, which it insists is * Windows 10. So we don't bother with it. (It may * indicate whether it's Home or Pro or..., but that's * not worth the effort of fixing the "Windows 11 is * Windows 10" nonsense.) * * https://patents.google.com/patent/EP1517235A2/en * * is a Microsoft patent that mentions the * BrandingFormatString() routine, and seems to suggest * that it dates back to at least Windows XP. * * https://dennisbabkin.com/blog/?t=how-to-tell-the-real-version-of-windows-your-app-is-running-on * * says that routine is in an undocumented winbrand.dll DLL, * but is used by Microsoft's own code to put the OS * product name into messages. It, unlike ProductName, * appears to make a distinction between Windows 10 and * Windows 11, and, when handed the string "%WINDOWS_LONG%", * gives the same edition decoration that I suspect * ProductName does. */ switch (win_version_info.dwMajorVersion) { case 3: case 4: /* NT 3.x and 4.x. */ g_string_append_printf(str, "Windows NT %lu.%lu", win_version_info.dwMajorVersion, win_version_info.dwMinorVersion); break; case 5: /* * W2K, WXP, and their server versions. * 3 cheers for Microsoft marketing! */ switch (win_version_info.dwMinorVersion) { case 0: g_string_append_printf(str, "Windows 2000"); break; case 1: g_string_append_printf(str, "Windows XP"); break; case 2: if (is_nt_workstation(&win_version_info) && (system_info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)) { g_string_append_printf(str, "Windows XP Professional x64 Edition"); } else { g_string_append_printf(str, "Windows Server 2003"); if (system_info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) g_string_append_printf(str, " x64 Edition"); } break; default: g_string_append_printf(str, "Windows NT, unknown version %lu.%lu", win_version_info.dwMajorVersion, win_version_info.dwMinorVersion); break; } break; case 6: { /* * Vista, W7, W8, W8.1, and their server versions. */ add_os_bitsize(str, &system_info); switch (win_version_info.dwMinorVersion) { case 0: g_string_append_printf(str, is_nt_workstation(&win_version_info) ? "Windows Vista" : "Windows Server 2008"); break; case 1: g_string_append_printf(str, is_nt_workstation(&win_version_info) ? "Windows 7" : "Windows Server 2008 R2"); break; case 2: g_string_append_printf(str, is_nt_workstation(&win_version_info) ? "Windows 8" : "Windows Server 2012"); break; case 3: g_string_append_printf(str, is_nt_workstation(&win_version_info) ? "Windows 8.1" : "Windows Server 2012 R2"); break; default: g_string_append_printf(str, "Windows NT, unknown version %lu.%lu", win_version_info.dwMajorVersion, win_version_info.dwMinorVersion); break; } break; } /* case 6 */ case 10: { /* * W10, W11, and their server versions. */ TCHAR ReleaseId[10]; DWORD ridSize = _countof(ReleaseId); add_os_bitsize(str, &system_info); switch (win_version_info.dwMinorVersion) { case 0: /* List of BuildNumber from https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions * and https://docs.microsoft.com/en-us/windows/release-health/windows11-release-information */ if (is_nt_workstation(&win_version_info)) { if (win_version_info.dwBuildNumber < 10240) { /* XXX - W10 builds before 10240? */ g_string_append_printf(str, "Windows"); } else if (win_version_info.dwBuildNumber < 22000){ /* W10 builds sstart at 10240 and end before 22000 */ g_string_append_printf(str, "Windows 10"); } else { /* Builds 22000 and later are W11 (until there's W12...). */ g_string_append_printf(str, "Windows 11"); } } else { switch (win_version_info.dwBuildNumber) { case 14393: g_string_append_printf(str, "Windows Server 2016"); break; case 17763: g_string_append_printf(str, "Windows Server 2019"); break; case 20348: g_string_append_printf(str, "Windows Server 2022"); break; default: g_string_append_printf(str, "Windows Server"); break; } } /* * Windows 10 and 11 have had multiple * releases, with different build numbers. * * The build number *could* be used to * determine the release string, but * that would require a table of releases * and strings, and that would have to * get updated whenever a new release * comes out, and that seems to happen * twice a year these days. * * The good news is that, under * * HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion * * there are two keys, DisplayVersion and * ReleaseId. If DisplayVersion is present, * it's a string that gives the release * string; if not, ReleaseId gives the * release string. * * The DisplayVersion value is currently * of the form YYHN, where YY is the * last two digits of the year, H stands * for "half", and N is the half of the * year in which it came out. * * The ReleaseId is just a numeric string * and for all the YYHN releases, it's * stuck at the same value. * * Note further that * * https://github.com/nvaccess/nvda/blob/master/source/winVersion.py * * has a comment claiming that * * From Version 1511 (build 10586), release * Id/display version comes from Windows * Registry. * However there are builds with no release * name (Version 1507/10240) or releases * with different builds. * Look these up first before asking * Windows Registry. * * "Look these up first" means "look them * up in a table that goes from * * 10240: Windows 10 1507 * * to * * 22621: Windows 11 22H2 * * and also includes * * 20348: Windows Server 2022 * * I'm not sure why any Windows 10 builds * after 10240 are in the table; what does * "releases with different builds" mean? * does it mean that those particular * builds have bogus ReleaseId or * DisplayVersion values? Those builds * appear to be official release builds * for W10/W11, according to the table * in * * https://en.wikipedia.org/wiki/Windows_NT * * so, if those are all necessary, why * should ReleaseId or DisplayVersion be * trusted at all? * * As for the Windows Server 2022 entry, * is that just becuase that script doesn't * bother checking for "workstation" vs. * "server"? */ if (RegGetValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"DisplayVersion", RRF_RT_REG_SZ, NULL, &ReleaseId, &ridSize) == ERROR_SUCCESS) { g_string_append_printf(str, " (%s)", utf_16to8(ReleaseId)); } else if (RegGetValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"ReleaseId", RRF_RT_REG_SZ, NULL, &ReleaseId, &ridSize) == ERROR_SUCCESS) { g_string_append_printf(str, " (%s)", utf_16to8(ReleaseId)); } break; default: g_string_append_printf(str, "Windows NT, unknown version %lu.%lu", win_version_info.dwMajorVersion, win_version_info.dwMinorVersion); break; } break; } /* case 10 */ default: g_string_append_printf(str, "Windows NT, unknown version %lu.%lu", win_version_info.dwMajorVersion, win_version_info.dwMinorVersion); break; } /* info.dwMajorVersion */ break; default: g_string_append_printf(str, "Unknown Windows platform %lu version %lu.%lu", win_version_info.dwPlatformId, win_version_info.dwMajorVersion, win_version_info.dwMinorVersion); break; } if (win_version_info.szCSDVersion[0] != '\0') g_string_append_printf(str, " %s", utf_16to8(win_version_info.szCSDVersion)); g_string_append_printf(str, ", build %lu", win_version_info.dwBuildNumber); #elif defined(HAVE_SYS_UTSNAME_H) struct utsname name; /* * We have <sys/utsname.h>, so we assume we have "uname()". */ if (uname(&name) < 0) { g_string_append_printf(str, "unknown OS version (uname failed - %s)", g_strerror(errno)); return; } if (strcmp(name.sysname, "AIX") == 0) { /* * Yay, IBM! Thanks for doing something different * from most of the other UNIXes out there, and * making "name.version" apparently be the major * version number and "name.release" be the minor * version number. */ g_string_append_printf(str, "%s %s.%s", name.sysname, name.version, name.release); } else { /* * XXX - get "version" on any other platforms? * * On Digital/Tru64 UNIX, it's something unknown. * On Solaris, it's some kind of build information. * On HP-UX, it appears to be some sort of subrevision * thing. * On *BSD and Darwin/macOS, it's a long string giving * a build date, config file name, etc., etc., etc.. */ #ifdef HAVE_MACOS_FRAMEWORKS /* * On macOS, report the macOS version number as the OS * version if we can, and put the Darwin information * in parentheses. */ if (get_macos_version_info(str)) { /* Success - append the Darwin information. */ g_string_append_printf(str, " (%s %s)", name.sysname, name.release); } else { /* Failure - just use the Darwin information. */ g_string_append_printf(str, "%s %s", name.sysname, name.release); } #else /* HAVE_MACOS_FRAMEWORKS */ /* * XXX - on Linux, are there any APIs to get the distribution * name and version number? I think some distributions have * that. * * At least on Linux Standard Base-compliant distributions, * there's an "lsb_release" command. However: * * http://forums.fedoraforum.org/showthread.php?t=220885 * * seems to suggest that if you don't have the redhat-lsb * package installed, you don't have lsb_release, and that * /etc/fedora-release has the release information on * Fedora. * * http://linux.die.net/man/1/lsb_release * * suggests that there's an /etc/distrib-release file, but * it doesn't indicate whether "distrib" is literally * "distrib" or is the name for the distribution, and * also speaks of an /etc/debian_version file. * * "lsb_release" apparently parses /etc/lsb-release, which * has shell-style assignments, assigning to, among other * values, DISTRIB_ID (distributor/distribution name), * DISTRIB_RELEASE (release number of the distribution), * DISTRIB_DESCRIPTION (*might* be name followed by version, * but the manpage for lsb_release seems to indicate that's * not guaranteed), and DISTRIB_CODENAME (code name, e.g. * "licentious" for the Ubuntu Licentious Lemur release). * the lsb_release man page also speaks of the distrib-release * file, but Debian doesn't have one, and Ubuntu 7's * lsb_release command doesn't look for one. * * I've seen references to /etc/redhat-release as well. * * See also * * http://bugs.python.org/issue1322 * * http://www.novell.com/coolsolutions/feature/11251.html * * http://linuxmafia.com/faq/Admin/release-files.html * * and the Lib/Platform.py file in recent Python 2.x * releases. * * And then there's /etc/os-release: * * https://0pointer.de/blog/projects/os-release * * which, apparently, is something that all distributions * with systemd have, which seems to mean "most distributions" * these days. It also has a list of several of the assorted * *other* such files that various distributions have. * * Maybe look at what pre-version-43 systemd does? 43 * removed support for the old files, but I guess that * means older versions *did* support them: * * https://lists.freedesktop.org/archives/systemd-devel/2012-February/004475.html * * At least on my Ubuntu 7 system, /etc/debian_version * doesn't contain anything interesting (just some Debian * codenames). It does have /etc/lsb-release. My Ubuntu * 22.04 system has /etc/lsb-release and /etc/os-release. * * My Fedora 9 system has /etc/fedora-release, with * /etc/redhat-release and /etc/system-release as symlinks * to it. They all just contain a one-line relase * description. My Fedora 38 system has that, plus * /etc/os-release. * * A quick Debian 3.1a installation I did has only * /etc/debian_version. My Debian 11.3 system has * /etc/os-release. * * See * * https://gist.github.com/natefoo/814c5bf936922dad97ff * * for descriptions of what some versions of some * distributions offer. * * So maybe have a table of files to try, with each * entry having a pathname, a pointer to a file parser * routine, and a pointer to a string giving a * parameter name passed to that routine, with entries * for: * * /etc/os-release, regular parser, "PRETTY_NAME" * /etc/lsb-release, regular parser, "DISTRIB_DESCRIPTION" * /etc/system-release, first line parser, NULL * /etc/redhat-release, first line parser, NULL * /etc/fedora-release, first line parser, NULL * /etc/centos-release, first line parser, NULL * /etc/debian_version, first line parser, "Debian" * /etc/SuSE-release, first line parser, NULL * /etc/slackware-version:, first line parser, NULL * /etc/gentoo-release, first line parser, NULL * /etc/antix-version, first line parser, NULL * * Each line is tried in order. If the open fails, go to * the next one. If the open succeeds but the parser * fails, close the file and go on to the next one. * * The regular parser parses files of the form * <param>="value". It's passed the value of <param> * for which to look; if not found, it fails. * * The first line parser reads the first line of the file. * If a string is passed to it, it constructs a distribution * name string by concatenating the parameter, a space, * and the contents of that line (iwth the newline removed), * otherwise it constructs it from the contents of the line. * * Fall back on just "Linux" if nothing works. * * Then use the uname() information to indicate what * kernel version the machine is running. * * XXX - for Gentoo, PRETTY_NAME might not give a version, * so fall back on /etc/gentoo-release? Gentoo is * a rolling-release distribution, so what *is* the * significance of the contnets of /etc/gentoo-release? * * XXX - MX appears to be a Debian-based distribution * whose /etc/os-release gives its Debian version and * whose /etc/mx-version and /etc/antix-version give * the MX version. Are there any other Debian derivatives * that do this? (The Big One calls itself "Ubuntu" * in PRETTY_NAME.) * * XXX - use ID_LIKE in /etc/os-release to check for, * for example, Debian-like distributions, e.g. when * suggesting how to give dumpcap capture privileges? */ g_string_append_printf(str, "%s %s", name.sysname, name.release); #endif /* HAVE_MACOS_FRAMEWORKS */ } #else g_string_append(str, "an unknown OS"); #endif } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/os_version_info.h
/** @file * Declarations of outines to report operating system version information * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WSUTIL_OS_VERSION_INFO_H__ #define __WSUTIL_OS_VERSION_INFO_H__ #include <wireshark.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Get the OS version, and append it to a GString. */ WS_DLL_PUBLIC void get_os_version_info(GString *str); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __WSUTIL_OS_VERSION_INFO_H__ */
Inno Setup Script
wireshark/wsutil/path_config.h.in
#ifndef __PATH_CONFIG_H__ #define __PATH_CONFIG_H__ #define INSTALL_PREFIX "@PATH_INSTALL_PREFIX@" #define DATA_DIR "@PATH_DATA_DIR@" #define DOC_DIR "@PATH_DOC_DIR@" #define PLUGIN_DIR "@PATH_PLUGIN_DIR@" #define EXTCAP_DIR "@PATH_EXTCAP_DIR@" #endif
C/C++
wireshark/wsutil/pint.h
/** @file * * Definitions for extracting and translating integers safely and portably * via pointers. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __PINT_H__ #define __PINT_H__ #include <glib.h> /* Routines that take a possibly-unaligned pointer to a 16-bit, 24-bit, * 32-bit, 40-bit, ... 64-bit integral quantity, in a particular byte * order, and fetch the value and return it in host byte order. * * The pntohN() routines fetch big-endian values; the pletohN() routines * fetch little-endian values. */ /* On most architectures, accesses of 16, 32, and 64 bit quantities can be * heavily optimized. gcc and clang recognize portable versions below and, * at -Os and higher, optimize them appropriately (for gcc, that includes * for z/Architecture, PPC64, MIPS, etc.). Older versions don't do as good * of a job with 16 bit accesses, though. * * Unfortunately, MSVC and icc (both the "classic" version and the new * LLVM-based Intel C Compiler) do not, according to Matt Godbolt's Compiler * Explorer (https://godbolt.org) as of the end of 2022. They *do* recognize * and optimize a memcpy based approach (which avoids unaligned accesses on, * say, ARM32), though that requires byteswapping appropriately. */ #if (defined(_MSC_VER) && !defined(__clang__)) || defined(__INTEL_COMPILER) || defined(__INTEL_LLVM_COMPILER) /* MSVC or Intel C Compiler (Classic or new LLVM version), but not * clang-cl on Windows. */ /* Unfortunately, C23 did not fully accept the N3022 Modern Bit Utilities * proposal, so a standard bytereverse function has been deferred for some * future version: * https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3048.htm * https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3022.htm * * So choose byteswap intrinsics we know we have. */ #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(__INTEL_LLVM_COMPILER) && !defined(__clang__) /* Intel and clang-cl both define _MSC_VER when compiling on Windows for * greater compatiblity (just as they define __GNUC__ on other platforms). * However, at least on some versions, while including the MSVC <stdlib.h> * provides access to the _byteswap_ intrinsics, they are not actually * optimized into a single x86 BSWAP function, unlike the gcc-style intrinsics * (which both support.) See: https://stackoverflow.com/q/72327906 */ #include <stdlib.h> // For MSVC _byteswap intrinsics #define pint_bswap16(x) _byteswap_ushort(x) #define pint_bswap32(x) _byteswap_ulong(x) /* Hopefully MSVC never decides that a long is 64 bit. */ #define pint_bswap64(x) _byteswap_uint64(x) #elif defined(__INTEL_COMPILER) /* The (deprecated) Intel C++ Compiler Classic has these byteswap intrinsics. * It also has the GCC-style intrinsics, though __builtin_bswap16 wasn't * added until some point after icc 13.0 but at least by 16.0, reflecting * that it wasn't added to gcc until 4.8. */ #define pint_bswap16(x) _bswap16(x) #define pint_bswap32(x) _bswap32(x) #define pint_bswap64(x) _bswap64(x) #else /* GCC-style _bswap intrinsics */ /* The new LLVM-based Intel C++ Compiler doesn't have the above intrinsics, * but it always has all the GCC intrinsics. */ /* __builtin_bswap32 and __builtin_bswap64 intrinsics have been supported * for a long time on gcc (4.1), and clang (pre 3.0), versions that predate * C11 and C+11 support, which we require, so we could assume we have them. * * __builtin_bswap16 was added a bit later, gcc 4.8, and clang 3.2. While * those versions or later are required for full C11 and C++11 support, * some earlier versions claim to support C11 and C++11 in ways that might * allow them to get past CMake. We don't use this codepath for those * compilers because they heavily optimize the portable versions, though. */ #define pint_bswap16(x) __builtin_bswap16(x) #define pint_bswap32(x) __builtin_bswap32(x) #define pint_bswap64(x) __builtin_bswap64(x) #endif static inline guint16 pntoh16(const void *p) { guint16 ret; memcpy(&ret, p, sizeof(ret)); #if G_BYTE_ORDER == G_LITTLE_ENDIAN ret = pint_bswap16(ret); #endif return ret; } static inline guint32 pntoh32(const void *p) { guint32 ret; memcpy(&ret, p, sizeof(ret)); #if G_BYTE_ORDER == G_LITTLE_ENDIAN ret = pint_bswap32(ret); #endif return ret; } static inline guint64 pntoh64(const void *p) { guint64 ret; memcpy(&ret, p, sizeof(ret)); #if G_BYTE_ORDER == G_LITTLE_ENDIAN ret = pint_bswap64(ret); #endif return ret; } static inline guint16 pletoh16(const void *p) { guint16 ret; memcpy(&ret, p, sizeof(ret)); #if G_BYTE_ORDER == G_BIG_ENDIAN ret = pint_bswap16(ret); #endif return ret; } static inline guint32 pletoh32(const void *p) { guint32 ret; memcpy(&ret, p, sizeof(ret)); #if G_BYTE_ORDER == G_BIG_ENDIAN ret = pint_bswap32(ret); #endif return ret; } static inline guint64 pletoh64(const void *p) { guint64 ret; memcpy(&ret, p, sizeof(ret)); #if G_BYTE_ORDER == G_BIG_ENDIAN ret = pint_bswap64(ret); #endif return ret; } static inline void phton16(guint8 *p, guint16 v) { #if G_BYTE_ORDER == G_LITTLE_ENDIAN v = pint_bswap16(v); #endif memcpy(p, &v, sizeof(v)); } static inline void phton32(guint8 *p, guint32 v) { #if G_BYTE_ORDER == G_LITTLE_ENDIAN v = pint_bswap32(v); #endif memcpy(p, &v, sizeof(v)); } static inline void phton64(guint8 *p, guint64 v) { #if G_BYTE_ORDER == G_LITTLE_ENDIAN v = pint_bswap64(v); #endif memcpy(p, &v, sizeof(v)); } static inline void phtole32(guint8 *p, guint32 v) { #if G_BYTE_ORDER == G_BIG_ENDIAN v = pint_bswap32(v); #endif memcpy(p, &v, sizeof(v)); } static inline void phtole64(guint8 *p, guint64 v) { #if G_BYTE_ORDER == G_BIG_ENDIAN v = pint_bswap64(v); #endif memcpy(p, &v, sizeof(v)); } #else /* Portable functions */ static inline guint16 pntoh16(const void *p) { return (guint16)*((const guint8 *)(p)+0)<<8| (guint16)*((const guint8 *)(p)+1)<<0; } static inline guint32 pntoh32(const void *p) { return (guint32)*((const guint8 *)(p)+0)<<24| (guint32)*((const guint8 *)(p)+1)<<16| (guint32)*((const guint8 *)(p)+2)<<8| (guint32)*((const guint8 *)(p)+3)<<0; } static inline guint64 pntoh64(const void *p) { return (guint64)*((const guint8 *)(p)+0)<<56| (guint64)*((const guint8 *)(p)+1)<<48| (guint64)*((const guint8 *)(p)+2)<<40| (guint64)*((const guint8 *)(p)+3)<<32| (guint64)*((const guint8 *)(p)+4)<<24| (guint64)*((const guint8 *)(p)+5)<<16| (guint64)*((const guint8 *)(p)+6)<<8| (guint64)*((const guint8 *)(p)+7)<<0; } static inline guint16 pletoh16(const void *p) { return (guint16)*((const guint8 *)(p)+1)<<8| (guint16)*((const guint8 *)(p)+0)<<0; } static inline guint32 pletoh32(const void *p) { return (guint32)*((const guint8 *)(p)+3)<<24| (guint32)*((const guint8 *)(p)+2)<<16| (guint32)*((const guint8 *)(p)+1)<<8| (guint32)*((const guint8 *)(p)+0)<<0; } static inline guint64 pletoh64(const void *p) { return (guint64)*((const guint8 *)(p)+7)<<56| (guint64)*((const guint8 *)(p)+6)<<48| (guint64)*((const guint8 *)(p)+5)<<40| (guint64)*((const guint8 *)(p)+4)<<32| (guint64)*((const guint8 *)(p)+3)<<24| (guint64)*((const guint8 *)(p)+2)<<16| (guint64)*((const guint8 *)(p)+1)<<8| (guint64)*((const guint8 *)(p)+0)<<0; } /* Pointer routines to put items out in a particular byte order. * These will work regardless of the byte alignment of the pointer. */ static inline void phton16(guint8 *p, guint16 v) { p[0] = (guint8)(v >> 8); p[1] = (guint8)(v >> 0); } static inline void phton32(guint8 *p, guint32 v) { p[0] = (guint8)(v >> 24); p[1] = (guint8)(v >> 16); p[2] = (guint8)(v >> 8); p[3] = (guint8)(v >> 0); } static inline void phton64(guint8 *p, guint64 v) { p[0] = (guint8)(v >> 56); p[1] = (guint8)(v >> 48); p[2] = (guint8)(v >> 40); p[3] = (guint8)(v >> 32); p[4] = (guint8)(v >> 24); p[5] = (guint8)(v >> 16); p[6] = (guint8)(v >> 8); p[7] = (guint8)(v >> 0); } static inline void phtole32(guint8 *p, guint32 v) { p[0] = (guint8)(v >> 0); p[1] = (guint8)(v >> 8); p[2] = (guint8)(v >> 16); p[3] = (guint8)(v >> 24); } static inline void phtole64(guint8 *p, guint64 v) { p[0] = (guint8)(v >> 0); p[1] = (guint8)(v >> 8); p[2] = (guint8)(v >> 16); p[3] = (guint8)(v >> 24); p[4] = (guint8)(v >> 32); p[5] = (guint8)(v >> 40); p[6] = (guint8)(v >> 48); p[7] = (guint8)(v >> 56); } #endif static inline guint32 pntoh24(const void *p) { return (guint32)*((const guint8 *)(p)+0)<<16| (guint32)*((const guint8 *)(p)+1)<<8| (guint32)*((const guint8 *)(p)+2)<<0; } static inline guint64 pntoh40(const void *p) { return (guint64)*((const guint8 *)(p)+0)<<32| (guint64)*((const guint8 *)(p)+1)<<24| (guint64)*((const guint8 *)(p)+2)<<16| (guint64)*((const guint8 *)(p)+3)<<8| (guint64)*((const guint8 *)(p)+4)<<0; } static inline guint64 pntoh48(const void *p) { return (guint64)*((const guint8 *)(p)+0)<<40| (guint64)*((const guint8 *)(p)+1)<<32| (guint64)*((const guint8 *)(p)+2)<<24| (guint64)*((const guint8 *)(p)+3)<<16| (guint64)*((const guint8 *)(p)+4)<<8| (guint64)*((const guint8 *)(p)+5)<<0; } static inline guint64 pntoh56(const void *p) { return (guint64)*((const guint8 *)(p)+0)<<48| (guint64)*((const guint8 *)(p)+1)<<40| (guint64)*((const guint8 *)(p)+2)<<32| (guint64)*((const guint8 *)(p)+3)<<24| (guint64)*((const guint8 *)(p)+4)<<16| (guint64)*((const guint8 *)(p)+5)<<8| (guint64)*((const guint8 *)(p)+6)<<0; } static inline guint32 pletoh24(const void *p) { return (guint32)*((const guint8 *)(p)+2)<<16| (guint32)*((const guint8 *)(p)+1)<<8| (guint32)*((const guint8 *)(p)+0)<<0; } static inline guint64 pletoh40(const void *p) { return (guint64)*((const guint8 *)(p)+4)<<32| (guint64)*((const guint8 *)(p)+3)<<24| (guint64)*((const guint8 *)(p)+2)<<16| (guint64)*((const guint8 *)(p)+1)<<8| (guint64)*((const guint8 *)(p)+0)<<0; } static inline guint64 pletoh48(const void *p) { return (guint64)*((const guint8 *)(p)+5)<<40| (guint64)*((const guint8 *)(p)+4)<<32| (guint64)*((const guint8 *)(p)+3)<<24| (guint64)*((const guint8 *)(p)+2)<<16| (guint64)*((const guint8 *)(p)+1)<<8| (guint64)*((const guint8 *)(p)+0)<<0; } static inline guint64 pletoh56(const void *p) { return (guint64)*((const guint8 *)(p)+6)<<48| (guint64)*((const guint8 *)(p)+5)<<40| (guint64)*((const guint8 *)(p)+4)<<32| (guint64)*((const guint8 *)(p)+3)<<24| (guint64)*((const guint8 *)(p)+2)<<16| (guint64)*((const guint8 *)(p)+1)<<8| (guint64)*((const guint8 *)(p)+0)<<0; } /* Subtract two guint32s with respect to wraparound */ #define guint32_wraparound_diff(higher, lower) ((higher>lower)?(higher-lower):(higher+0xffffffff-lower+1)) #endif /* PINT_H */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * 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: */
C
wireshark/wsutil/please_report_bug.c
/* please_report_bug.c * Routines returning strings to use when reporting a bug. * They ask the user to report a bug to the Wireshark developers. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "please_report_bug.h" /* * Long message, to use in alert boxes and printed messages. */ const char * please_report_bug(void) { return "Please report this to the Wireshark developers as a bug.\n" "https://gitlab.com/wireshark/wireshark/issues\n" "(This is not a crash; please do not say, in your report, that it is a crash.)"; } /* * Short message, to use in status bar messages. */ const char * please_report_bug_short(void) { return "Please report this to the Wireshark developers."; }
C/C++
wireshark/wsutil/please_report_bug.h
/** @file * Declarations of routines returning strings to use when reporting a bug. * They ask the user to report a bug to the Wireshark developers. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __PLEASE_REPORT_BUG_H__ #define __PLEASE_REPORT_BUG_H__ #include "ws_symbol_export.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Long message, to use in alert boxes and printed messages. */ WS_DLL_PUBLIC const char *please_report_bug(void); /* * Short message, to use in status bar messages. */ WS_DLL_PUBLIC const char *please_report_bug_short(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __PLEASE_REPORT_BUG_H__ */
C
wireshark/wsutil/plugins.c
/* plugins.c * plugin routines * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #define WS_LOG_DOMAIN LOG_DOMAIN_PLUGINS #include "plugins.h" #include <time.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <gmodule.h> #include <wsutil/filesystem.h> #include <wsutil/privileges.h> #include <wsutil/file_util.h> #include <wsutil/report_message.h> #include <wsutil/wslog.h> typedef struct _plugin { GModule *handle; /* handle returned by g_module_open */ gchar *name; /* plugin name */ const gchar *version; /* plugin version */ const gchar *type_name; /* user-facing name (what it does). Should these be capitalized? */ } plugin; #define TYPE_DIR_EPAN "epan" #define TYPE_DIR_WIRETAP "wiretap" #define TYPE_DIR_CODECS "codecs" #define TYPE_NAME_DISSECTOR "dissector" #define TYPE_NAME_FILE_TYPE "file type" #define TYPE_NAME_CODEC "codec" static GSList *plugins_module_list = NULL; static inline const char * type_to_dir(plugin_type_e type) { switch (type) { case WS_PLUGIN_EPAN: return TYPE_DIR_EPAN; case WS_PLUGIN_WIRETAP: return TYPE_DIR_WIRETAP; case WS_PLUGIN_CODEC: return TYPE_DIR_CODECS; default: ws_error("Unknown plugin type: %u. Aborting.", (unsigned) type); break; } ws_assert_not_reached(); } static inline const char * type_to_name(plugin_type_e type) { switch (type) { case WS_PLUGIN_EPAN: return TYPE_NAME_DISSECTOR; case WS_PLUGIN_WIRETAP: return TYPE_NAME_FILE_TYPE; case WS_PLUGIN_CODEC: return TYPE_NAME_CODEC; default: ws_error("Unknown plugin type: %u. Aborting.", (unsigned) type); break; } ws_assert_not_reached(); } static void free_plugin(gpointer data) { plugin *p = (plugin *)data; g_module_close(p->handle); g_free(p->name); g_free(p); } static gint compare_plugins(gconstpointer a, gconstpointer b) { return g_strcmp0((*(plugin *const *)a)->name, (*(plugin *const *)b)->name); } static gboolean pass_plugin_version_compatibility(GModule *handle, const char *name) { gpointer symb; int major, minor; if(!g_module_symbol(handle, "plugin_want_major", &symb)) { report_failure("The plugin '%s' has no \"plugin_want_major\" symbol", name); return FALSE; } major = *(int *)symb; if(!g_module_symbol(handle, "plugin_want_minor", &symb)) { report_failure("The plugin '%s' has no \"plugin_want_minor\" symbol", name); return FALSE; } minor = *(int *)symb; if (major != VERSION_MAJOR || minor != VERSION_MINOR) { report_failure("The plugin '%s' was compiled for Wireshark version %d.%d", name, major, minor); return FALSE; } return TRUE; } // GLib and Qt allow ".dylib" and ".so" on macOS. Should we do the same? #ifdef _WIN32 #define MODULE_SUFFIX ".dll" #else #define MODULE_SUFFIX ".so" #endif static void scan_plugins_dir(GHashTable *plugins_module, const char *dirpath, plugin_type_e type, gboolean append_type) { GDir *dir; const char *name; /* current file name */ gchar *plugin_folder; gchar *plugin_file; /* current file full path */ GModule *handle; /* handle returned by g_module_open */ gpointer symbol; const char *plug_version; plugin *new_plug; if (append_type) plugin_folder = g_build_filename(dirpath, type_to_dir(type), (gchar *)NULL); else plugin_folder = g_strdup(dirpath); dir = g_dir_open(plugin_folder, 0, NULL); if (dir == NULL) { g_free(plugin_folder); return; } ws_debug("Scanning plugins folder \"%s\"", plugin_folder); while ((name = g_dir_read_name(dir)) != NULL) { /* Skip anything but files with .dll or .so. */ if (!g_str_has_suffix(name, MODULE_SUFFIX)) continue; /* * Check if the same name is already registered. */ if (g_hash_table_lookup(plugins_module, name)) { /* Yes, it is. */ report_warning("The plugin '%s' was found " "in multiple directories", name); continue; } plugin_file = g_build_filename(plugin_folder, name, (gchar *)NULL); handle = g_module_open(plugin_file, G_MODULE_BIND_LOCAL); if (handle == NULL) { /* g_module_error() provides file path. */ report_failure("Couldn't load plugin '%s': %s", name, g_module_error()); g_free(plugin_file); continue; } if (!g_module_symbol(handle, "plugin_version", &symbol)) { report_failure("The plugin '%s' has no \"plugin_version\" symbol", name); g_module_close(handle); g_free(plugin_file); continue; } plug_version = (const char *)symbol; if (!pass_plugin_version_compatibility(handle, name)) { g_module_close(handle); g_free(plugin_file); continue; } /* Search for the entry point for the plugin registration function */ if (!g_module_symbol(handle, "plugin_register", &symbol)) { report_failure("The plugin '%s' has no \"plugin_register\" symbol", name); g_module_close(handle); g_free(plugin_file); continue; } DIAG_OFF_PEDANTIC /* Found it, call the plugin registration function. */ ((plugin_register_func)symbol)(); DIAG_ON_PEDANTIC new_plug = g_new(plugin, 1); new_plug->handle = handle; new_plug->name = g_strdup(name); new_plug->version = plug_version; new_plug->type_name = type_to_name(type); /* Add it to the list of plugins. */ g_hash_table_replace(plugins_module, new_plug->name, new_plug); ws_info("Registered plugin: %s (%s)", new_plug->name, plugin_file); g_free(plugin_file); } ws_dir_close(dir); g_free(plugin_folder); } /* * Scan for plugins. */ plugins_t * plugins_init(plugin_type_e type) { if (!g_module_supported()) return NULL; /* nothing to do */ GHashTable *plugins_module = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, free_plugin); /* * Scan the global plugin directory. */ scan_plugins_dir(plugins_module, get_plugins_dir_with_version(), type, TRUE); /* * If the program wasn't started with special privileges, * scan the users plugin directory. (Even if we relinquish * them, plugins aren't safe unless we've *permanently* * relinquished them, and we can't do that in Wireshark as, * if we need privileges to start capturing, we'd need to * reclaim them before each time we start capturing.) */ if (!started_with_special_privs()) { scan_plugins_dir(plugins_module, get_plugins_pers_dir_with_version(), type, TRUE); } plugins_module_list = g_slist_prepend(plugins_module_list, plugins_module); return plugins_module; } WS_DLL_PUBLIC void plugins_get_descriptions(plugin_description_callback callback, void *callback_data) { GPtrArray *plugins_array = g_ptr_array_new(); GHashTableIter iter; gpointer value; for (GSList *l = plugins_module_list; l != NULL; l = l->next) { g_hash_table_iter_init (&iter, (GHashTable *)l->data); while (g_hash_table_iter_next (&iter, NULL, &value)) { g_ptr_array_add(plugins_array, value); } } g_ptr_array_sort(plugins_array, compare_plugins); for (guint i = 0; i < plugins_array->len; i++) { plugin *plug = (plugin *)plugins_array->pdata[i]; callback(plug->name, plug->version, plug->type_name, g_module_name(plug->handle), callback_data); } g_ptr_array_free(plugins_array, TRUE); } static void print_plugin_description(const char *name, const char *version, const char *description, const char *filename, void *user_data _U_) { printf("%-16s\t%s\t%s\t%s\n", name, version, description, filename); } void plugins_dump_all(void) { plugins_get_descriptions(print_plugin_description, NULL); } int plugins_get_count(void) { guint count = 0; for (GSList *l = plugins_module_list; l != NULL; l = l->next) { count += g_hash_table_size((GHashTable *)l->data); } return count; } void plugins_cleanup(plugins_t *plugins) { if (!plugins) return; plugins_module_list = g_slist_remove(plugins_module_list, plugins); g_hash_table_destroy((GHashTable *)plugins); } gboolean plugins_supported(void) { return g_module_supported(); } /* * 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: */
C/C++
wireshark/wsutil/plugins.h
/** @file * definitions for plugins structures * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __PLUGINS_H__ #define __PLUGINS_H__ #include <wireshark.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ typedef void (*plugin_register_func)(void); typedef void plugins_t; typedef enum { WS_PLUGIN_EPAN, WS_PLUGIN_WIRETAP, WS_PLUGIN_CODEC } plugin_type_e; WS_DLL_PUBLIC plugins_t *plugins_init(plugin_type_e type); typedef void (*plugin_description_callback)(const char *name, const char *version, const char *types, const char *filename, void *user_data); WS_DLL_PUBLIC void plugins_get_descriptions(plugin_description_callback callback, void *user_data); WS_DLL_PUBLIC void plugins_dump_all(void); WS_DLL_PUBLIC int plugins_get_count(void); WS_DLL_PUBLIC void plugins_cleanup(plugins_t *plugins); WS_DLL_PUBLIC gboolean plugins_supported(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __PLUGINS_H__ */ /* * 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: */
C/C++
wireshark/wsutil/pow2.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_POW2_H__ #define __WS_POW2_H__ /* * Macros to calculate pow2^M, for various power-of-2 values and positive * integer values of M. That's (2^N)^M, i.e. 2^(N*M). * * The first argument is the type of the desired result; the second * argument is M. */ #define pow2(type, m) (((type)1U) << (m)) #define pow4(type, m) (((type)1U) << (2*(m))) #define pow8(type, m) (((type)1U) << (3*(m))) #define pow16(type, m) (((type)1U) << (4*(m))) #define pow32(type, m) (((type)1U) << (5*(m))) #define pow64(type, m) (((type)1U) << (6*(m))) #define pow128(type, m) (((type)1U) << (7*(m))) #define pow256(type, m) (((type)1U) << (8*(m))) #endif /* __WS_POW2_H__ */
C
wireshark/wsutil/privileges.c
/* privileges.c * Routines for handling privileges, e.g. set-UID and set-GID on UNIX. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2006 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #define WS_LOG_DOMAIN LOG_DOMAIN_WSUTIL #if defined(HAVE_SETRESUID) || defined(HAVE_SETREGUID) #define _GNU_SOURCE /* Otherwise [sg]etres[gu]id won't be defined on Linux */ #endif #include "privileges.h" #include <wsutil/ws_assert.h> #include <wsutil/wslog.h> #ifdef _WIN32 #include <windows.h> #include <wchar.h> #include <tchar.h> /* * Called when the program starts, to save whatever credential information * we'll need later, and to do whatever other specialized platform-dependent * initialization we want. */ void init_process_policies(void) { /* * If we have SetProcessDEPPolicy(), turn "data execution * prevention" on - i.e., if the MMU lets you set execute * permission on a per-page basis, turn execute permission * off on most data pages. SetProcessDEPPolicy() fails on * 64-bit Windows (it's *always* on there), but if it fails, * we don't care (we did our best), so we don't check for * errors. * */ SetProcessDEPPolicy(PROCESS_DEP_ENABLE); } /* * For now, we say the program wasn't started with special privileges. * There are ways of running programs with credentials other than those * for the session in which it's run, but I don't know whether that'd be * done with Wireshark/TShark or not. */ gboolean started_with_special_privs(void) { return FALSE; } /* * For now, we say the program isn't running with special privileges. * There are ways of running programs with credentials other than those * for the session in which it's run, but I don't know whether that'd be * done with Wireshark/TShark or not. */ gboolean running_with_special_privs(void) { return FALSE; } /* * For now, we don't do anything when asked to relinquish special privileges. */ void relinquish_special_privs_perm(void) { } /* * Get the current username. String must be g_free()d after use. */ gchar * get_cur_username(void) { gchar *username; username = g_strdup("UNKNOWN"); return username; } /* * Get the current group. String must be g_free()d after use. */ gchar * get_cur_groupname(void) { gchar *groupname; groupname = g_strdup("UNKNOWN"); return groupname; } #else /* _WIN32 */ #include <sys/types.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_PWD_H #include <pwd.h> #endif #ifdef HAVE_GRP_H #include <grp.h> #endif #include <string.h> #include <errno.h> static uid_t ruid, euid; static gid_t rgid, egid; static gboolean init_process_policies_called = FALSE; /* * Called when the program starts, to save whatever credential information * we'll need later, and to do whatever other specialized platform-dependent * initialization we want. * * The credential information we'll need later on UNIX is the real and * effective UID and GID. * * XXX - do any UN*Xes have opt-in "no execute on data pages by default" * permission? This would be the place to request it. */ void init_process_policies(void) { ruid = getuid(); euid = geteuid(); rgid = getgid(); egid = getegid(); init_process_policies_called = TRUE; } /* * "Started with special privileges" means "started out set-UID or set-GID", * or run as the root user or group. */ gboolean started_with_special_privs(void) { ws_assert(init_process_policies_called); #ifdef HAVE_ISSETUGID return issetugid(); #else return (ruid != euid || rgid != egid || ruid == 0 || rgid == 0); #endif } /* * Return TRUE if the real, effective, or saved (if we can check it) user * ID or group are 0. */ gboolean running_with_special_privs(void) { #ifdef HAVE_SETRESUID uid_t ru, eu, su; #endif #ifdef HAVE_SETRESGID gid_t rg, eg, sg; #endif #ifdef HAVE_SETRESUID getresuid(&ru, &eu, &su); if (ru == 0 || eu == 0 || su == 0) return TRUE; #else if (getuid() == 0 || geteuid() == 0) return TRUE; #endif #ifdef HAVE_SETRESGID getresgid(&rg, &eg, &sg); if (rg == 0 || eg == 0 || sg == 0) return TRUE; #else if (getgid() == 0 || getegid() == 0) return TRUE; #endif return FALSE; } /* * Permanently relinquish set-UID and set-GID privileges. * If error, abort since we probably shouldn't continue * with elevated privileges. * Note that if this error occurs when dumpcap is called from * wireshark or tshark, the message seen will be * "Child dumpcap process died:". This is obscure but we'll * consider it acceptable since it should be highly unlikely * that this error will occur. */ static void setxid_fail(const gchar *str) { ws_error("Attempt to relinquish privileges failed [%s()] - aborting: %s\n", str, g_strerror(errno)); } void relinquish_special_privs_perm(void) { /* * If we were started with special privileges, set the * real and effective group and user IDs to the original * values of the real and effective group and user IDs. * If we're not, don't bother - doing so seems to mung * our group set, at least in Mac OS X 10.5. * * (Set the effective UID last - that takes away our * rights to set anything else.) */ if (started_with_special_privs()) { #ifdef HAVE_SETRESGID if (setresgid(rgid, rgid, rgid) == -1) {setxid_fail("setresgid");} #else if (setgid(rgid) == -1) {setxid_fail("setgid"); } if (setegid(rgid) == -1) {setxid_fail("setegid");} #endif #ifdef HAVE_SETRESUID if (setresuid(ruid, ruid, ruid) == -1) {setxid_fail("setresuid");} #else if (setuid(ruid) == -1) {setxid_fail("setuid"); } if (seteuid(ruid) == -1) {setxid_fail("seteuid");} #endif } } /* * Get the current username. String must be g_free()d after use. */ gchar * get_cur_username(void) { gchar *username; struct passwd *pw = getpwuid(getuid()); if (pw) { username = g_strdup(pw->pw_name); } else { username = g_strdup("UNKNOWN"); } endpwent(); return username; } /* * Get the current group. String must be g_free()d after use. */ gchar * get_cur_groupname(void) { gchar *groupname; struct group *gr = getgrgid(getgid()); if (gr) { groupname = g_strdup(gr->gr_name); } else { groupname = g_strdup("UNKNOWN"); } endgrent(); return groupname; } #endif /* _WIN32 */ /* * Editor modelines * * Local Variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * ex: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/privileges.h
/** @file * Declarations of routines for handling privileges. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2006 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __PRIVILEGES_H__ #define __PRIVILEGES_H__ #include <wireshark.h> #ifdef __cplusplus extern "C" { #endif /** * Called when the program starts, to enable security features and save * whatever credential information we'll need later. */ WS_DLL_PUBLIC void init_process_policies(void); /** * Was this program started with special privileges? get_credential_info() * MUST be called before calling this. * @return TRUE if the program was started with special privileges, * FALSE otherwise. */ WS_DLL_PUBLIC gboolean started_with_special_privs(void); /** * Is this program running with special privileges? get_credential_info() * MUST be called before calling this. * @return TRUE if the program is running with special privileges, * FALSE otherwise. */ WS_DLL_PUBLIC gboolean running_with_special_privs(void); /** * Permanently relinquish special privileges. get_credential_info() * MUST be called before calling this. */ WS_DLL_PUBLIC void relinquish_special_privs_perm(void); /** * Get the current username. String must be g_free()d after use. * @return A freshly g_alloc()ed string containing the username, * or "UNKNOWN" on failure. */ WS_DLL_PUBLIC gchar *get_cur_username(void); /** * Get the current group. String must be g_free()d after use. * @return A freshly g_alloc()ed string containing the group, * or "UNKNOWN" on failure. */ WS_DLL_PUBLIC gchar *get_cur_groupname(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __PRIVILEGES_H__ */
C/C++
wireshark/wsutil/processes.h
/** @file * * Process utility definitions * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef _WSUTIL_PROCESSES_H_ #define _WSUTIL_PROCESSES_H_ #include "ws_symbol_export.h" #ifdef _WIN32 /* * On Windows, a process ID is a HANDLE. * Include <windows.h> to make sure HANDLE is defined. */ #include <windows.h> #else /* * On UN*X, a process ID is a pid_t. * Include <sys/types.h> to make sure pid_t is defined. */ #include <sys/types.h> #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef _WIN32 /* * On Windows, a process ID is a HANDLE. */ typedef HANDLE ws_process_id; #define WS_INVALID_PID INVALID_HANDLE_VALUE #else /* * On UN*X, a process ID is a pid_t. */ typedef pid_t ws_process_id; #define WS_INVALID_PID -1 #endif #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _WSUTIL_PROCESSES_H_ */
C
wireshark/wsutil/regex.c
/* * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "regex.h" #include <wsutil/ws_return.h> #include <wsutil/str_util.h> #include <pcre2.h> struct _ws_regex { pcre2_code *code; char *pattern; }; #define ERROR_MAXLEN_IN_CODE_UNITS 128 static char * get_error_msg(int errorcode) { char *buffer; /* * We have to provide a buffer and we don't know how long the * error message is or even the maximum size. From pcre2api(3): * "None of the messages are very long; a * buffer size of 120 code units is ample." */ /* Code unit = one byte */ buffer = g_malloc(ERROR_MAXLEN_IN_CODE_UNITS); /* Message is returned with a trailing zero. */ pcre2_get_error_message(errorcode, buffer, ERROR_MAXLEN_IN_CODE_UNITS); /* One more at the end for good luck. */ buffer[ERROR_MAXLEN_IN_CODE_UNITS-1] = '\0'; return buffer; } static pcre2_code * compile_pcre2(const char *patt, ssize_t size, char **errmsg, unsigned flags) { pcre2_code *code; int errorcode; PCRE2_SIZE length; PCRE2_SIZE erroroffset; uint32_t options = 0; if (size < 0) length = PCRE2_ZERO_TERMINATED; else length = (PCRE2_SIZE)size; if (flags & WS_REGEX_NEVER_UTF) options |= PCRE2_NEVER_UTF; if (flags & WS_REGEX_CASELESS) options |= PCRE2_CASELESS; /* By default UTF-8 is off. */ code = pcre2_compile_8((PCRE2_SPTR)patt, length, options, &errorcode, &erroroffset, NULL); if (code == NULL) { *errmsg = get_error_msg(errorcode); return NULL; } return code; } ws_regex_t * ws_regex_compile_ex(const char *patt, ssize_t size, char **errmsg, unsigned flags) { ws_return_val_if_null(patt, NULL); pcre2_code *code = compile_pcre2(patt, size, errmsg, flags); if (code == NULL) return NULL; ws_regex_t *re = g_new(ws_regex_t, 1); re->code = code; re->pattern = ws_escape_string_len(NULL, patt, size, false); return re; } ws_regex_t * ws_regex_compile(const char *patt, char **errmsg) { return ws_regex_compile_ex(patt, -1, errmsg, 0); } static bool match_pcre2(pcre2_code *code, const char *subject, ssize_t subj_length, pcre2_match_data *match_data) { PCRE2_SIZE length; int rc; if (subj_length < 0) length = PCRE2_ZERO_TERMINATED; else length = (PCRE2_SIZE)subj_length; rc = pcre2_match(code, subject, length, 0, /* start at offset zero of the subject */ 0, /* default options */ match_data, NULL); if (rc < 0) { /* No match */ if (rc != PCRE2_ERROR_NOMATCH) { /* Error. Should not happen with UTF-8 disabled. Some huge * subject strings could hit some internal limit. */ char *msg = get_error_msg(rc); ws_debug("Unexpected pcre2_match() error: %s.", msg); g_free(msg); } return FALSE; } /* Matched */ return TRUE; } bool ws_regex_matches(const ws_regex_t *re, const char *subj) { return ws_regex_matches_length(re, subj, -1); } bool ws_regex_matches_length(const ws_regex_t *re, const char *subj, ssize_t subj_length) { bool matched; pcre2_match_data *match_data; ws_return_val_if_null(re, FALSE); ws_return_val_if_null(subj, FALSE); /* We don't use the matched substring but pcre2_match requires * at least one pair of offsets. */ match_data = pcre2_match_data_create(1, NULL); matched = match_pcre2(re->code, subj, subj_length, match_data); pcre2_match_data_free(match_data); return matched; } bool ws_regex_matches_pos(const ws_regex_t *re, const char *subj, ssize_t subj_length, size_t pos_vect[2]) { bool matched; pcre2_match_data *match_data; ws_return_val_if_null(re, FALSE); ws_return_val_if_null(subj, FALSE); match_data = pcre2_match_data_create(1, NULL); matched = match_pcre2(re->code, subj, subj_length, match_data); if (matched && pos_vect) { PCRE2_SIZE *ovect = pcre2_get_ovector_pointer(match_data); pos_vect[0] = ovect[0]; pos_vect[1] = ovect[1]; } pcre2_match_data_free(match_data); return matched; } void ws_regex_free(ws_regex_t *re) { pcre2_code_free(re->code); g_free(re->pattern); g_free(re); } const char * ws_regex_pattern(const ws_regex_t *re) { return re->pattern; }
C/C++
wireshark/wsutil/regex.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WSUTIL_REGEX_H__ #define __WSUTIL_REGEX_H__ #include <wireshark.h> #ifdef __cplusplus extern "C" { #endif struct _ws_regex; typedef struct _ws_regex ws_regex_t; WS_DLL_PUBLIC ws_regex_t * ws_regex_compile(const char *patt, char **errmsg); #define WS_REGEX_CASELESS (1U << 0) /* By default UTF-8 is off. This option also prevents it from being * turned on using a pattern option. */ #define WS_REGEX_NEVER_UTF (1U << 1) WS_DLL_PUBLIC ws_regex_t * ws_regex_compile_ex(const char *patt, ssize_t size, char **errmsg, unsigned flags); /** Matches a null-terminated subject string. */ WS_DLL_PUBLIC bool ws_regex_matches(const ws_regex_t *re, const char *subj); /** Matches a subject string length in 8 bit code units. */ WS_DLL_PUBLIC bool ws_regex_matches_length(const ws_regex_t *re, const char *subj, ssize_t subj_length); /** Returns start and end position of the matched substring. * * pos_vect[0] is first codepoint in the matched substring. * pos_vect[1] is the next to last codepoint in the matched substring. * pos_vect[1] - pos_vect[0] is the matched substring length. */ WS_DLL_PUBLIC bool ws_regex_matches_pos(const ws_regex_t *re, const char *subj, ssize_t subj_length, size_t pos_vect[2]); WS_DLL_PUBLIC void ws_regex_free(ws_regex_t *re); WS_DLL_PUBLIC const char * ws_regex_pattern(const ws_regex_t *re); #ifdef __cplusplus } #endif #endif /* __WSUTIL_REGEX_H__ */
C
wireshark/wsutil/report_message.c
/* report_message.c * Routines for code that can run in GUI and command-line environments to * use to report errors and warnings to the user (e.g., I/O errors, or * problems with preference settings) if the message should be shown as * a GUI error in a GUI environment. * * The application using libwsutil will register error-reporting * routines, and the routines defined here will call the registered * routines. That way, these routines can be called by code that * doesn't itself know whether to pop up a dialog or print something * to the standard error. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "report_message.h" static const char *friendly_program_name; static const struct report_message_routines *routines; void init_report_message(const char *friendly_program_name_arg, const struct report_message_routines *routines_arg) { friendly_program_name = friendly_program_name_arg; routines = routines_arg; } /* * Report a general error. */ void report_failure(const char *msg_format, ...) { va_list ap; va_start(ap, msg_format); (*routines->vreport_failure)(msg_format, ap); va_end(ap); } /* * Report a general warning. */ void report_warning(const char *msg_format, ...) { va_list ap; va_start(ap, msg_format); (*routines->vreport_warning)(msg_format, ap); va_end(ap); } /* * Report an error when trying to open or create a file. * "err" is assumed to be an error code from Wiretap; positive values are * UNIX-style errnos, so this can be used for open failures not from * Wiretap as long as the failure code is just an errno. */ void report_open_failure(const char *filename, int err, gboolean for_writing) { (*routines->report_open_failure)(filename, err, for_writing); } /* * Report an error when trying to read a file. * "err" is assumed to be a UNIX-style errno. */ void report_read_failure(const char *filename, int err) { (*routines->report_read_failure)(filename, err); } /* * Report an error when trying to write a file. * "err" is assumed to be a UNIX-style errno. */ void report_write_failure(const char *filename, int err) { (*routines->report_write_failure)(filename, err); } /* * Report an error from opening a capture file for reading. */ void report_cfile_open_failure(const char *filename, int err, gchar *err_info) { (*routines->report_cfile_open_failure)(filename, err, err_info); } /* * Report an error from opening a capture file for writing. */ void report_cfile_dump_open_failure(const char *filename, int err, gchar *err_info, int file_type_subtype) { (*routines->report_cfile_dump_open_failure)(filename, err, err_info, file_type_subtype); } /* * Report an error from attempting to read from a capture file. */ void report_cfile_read_failure(const char *filename, int err, gchar *err_info) { (*routines->report_cfile_read_failure)(filename, err, err_info); } /* * Report an error from attempting to write to a capture file. */ void report_cfile_write_failure(const char *in_filename, const char *out_filename, int err, gchar *err_info, guint32 framenum, int file_type_subtype) { (*routines->report_cfile_write_failure)(in_filename, out_filename, err, err_info, framenum, file_type_subtype); } /* * Report an error from closing a capture file open for writing. */ void report_cfile_close_failure(const char *filename, int err, gchar *err_info) { (*routines->report_cfile_close_failure)(filename, err, err_info); } /* * Return the "friendly" program name. */ const char * get_friendly_program_name(void) { return friendly_program_name; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/report_message.h
/** @file * Declarations of routines for code that can run in GUI and command-line * environments to use to report errors and warnings to the user (e.g., * I/O errors, or problems with preference settings) if the message should * be shown as a GUI error in a GUI environment. * * The application using libwsutil will register message-reporting * routines, and the routines declared here will call the registered * routines. That way, these routines can be called by code that * doesn't itself know whether to pop up a dialog or print something * to the standard error. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __REPORT_MESSAGE_H__ #define __REPORT_MESSAGE_H__ #include <wireshark.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Initialize the report message routines */ struct report_message_routines { void (*vreport_failure)(const char *, va_list); void (*vreport_warning)(const char *, va_list); void (*report_open_failure)(const char *, int, gboolean); void (*report_read_failure)(const char *, int); void (*report_write_failure)(const char *, int); void (*report_cfile_open_failure)(const char *, int, gchar *); void (*report_cfile_dump_open_failure)(const char *, int, gchar *, int); void (*report_cfile_read_failure)(const char *, int, gchar *); void (*report_cfile_write_failure)(const char *, const char *, int, gchar *, guint32, int); void (*report_cfile_close_failure)(const char *, int, gchar *); }; WS_DLL_PUBLIC void init_report_message(const char *friendly_program_name, const struct report_message_routines *routines); /* * Report a general error. */ WS_DLL_PUBLIC void report_failure(const char *msg_format, ...) G_GNUC_PRINTF(1, 2); /* * Report a general warning. */ WS_DLL_PUBLIC void report_warning(const char *msg_format, ...) G_GNUC_PRINTF(1, 2); /* * Report an error when trying to open a file. * "err" is assumed to be an error code from Wiretap; positive values are * UNIX-style errnos, so this can be used for open failures not from * Wiretap as long as the failure code is just an errno. */ WS_DLL_PUBLIC void report_open_failure(const char *filename, int err, gboolean for_writing); /* * Report an error when trying to read a file. * "err" is assumed to be a UNIX-style errno. */ WS_DLL_PUBLIC void report_read_failure(const char *filename, int err); /* * Report an error when trying to write a file. * "err" is assumed to be a UNIX-style errno. */ WS_DLL_PUBLIC void report_write_failure(const char *filename, int err); /* * Report an error from opening a capture file for reading. */ WS_DLL_PUBLIC void report_cfile_open_failure(const char *filename, int err, gchar *err_info); /* * Report an error from opening a capture file for writing. */ WS_DLL_PUBLIC void report_cfile_dump_open_failure(const char *filename, int err, gchar *err_info, int file_type_subtype); /* * Report an error from attempting to read from a capture file. */ WS_DLL_PUBLIC void report_cfile_read_failure(const char *filename, int err, gchar *err_info); /* * Report an error from attempting to write to a capture file. */ WS_DLL_PUBLIC void report_cfile_write_failure(const char *in_filename, const char *out_filename, int err, gchar *err_info, guint32 framenum, int file_type_subtype); /* * Report an error from closing a capture file open for writing. */ WS_DLL_PUBLIC void report_cfile_close_failure(const char *filename, int err, gchar *err_info); /* * Return the "friendly" program name. */ WS_DLL_PUBLIC const char *get_friendly_program_name(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __REPORT_MESSAGE_H__ */
C
wireshark/wsutil/rsa.c
/* rsa.c * * Functions for RSA private key reading and use * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2007 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #define WS_LOG_DOMAIN LOG_DOMAIN_WSUTIL #include "rsa.h" #include "filesystem.h" #include "file_util.h" #include <errno.h> #include <wsutil/wslog.h> #ifdef HAVE_LIBGNUTLS #include <gnutls/abstract.h> #include <gnutls/pkcs12.h> /* RSA private key file processing {{{ */ #define RSA_PARS 6 gcry_sexp_t rsa_privkey_to_sexp(gnutls_x509_privkey_t priv_key, char **err) { gnutls_datum_t rsa_datum[RSA_PARS]; /* m, e, d, p, q, u */ size_t tmp_size; gcry_error_t gret; gcry_sexp_t rsa_priv_key = NULL; gint i; gcry_mpi_t rsa_params[RSA_PARS]; *err = NULL; /* RSA get parameter */ if (gnutls_x509_privkey_export_rsa_raw(priv_key, &rsa_datum[0], &rsa_datum[1], &rsa_datum[2], &rsa_datum[3], &rsa_datum[4], &rsa_datum[5]) != 0) { *err = g_strdup("can't export rsa param (is a rsa private key file ?!?)"); return NULL; } /* convert each rsa parameter to mpi format*/ for(i=0; i<RSA_PARS; i++) { gret = gcry_mpi_scan(&rsa_params[i], GCRYMPI_FMT_USG, rsa_datum[i].data, rsa_datum[i].size,&tmp_size); /* these buffers were allocated by gnutls_x509_privkey_export_rsa_raw() */ g_free(rsa_datum[i].data); if (gret != 0) { *err = ws_strdup_printf("can't convert m rsa param to int (size %d)", rsa_datum[i].size); return NULL; } } /* libgcrypt expects p < q, and gnutls might not return it as such, depending on gnutls version and its crypto backend */ if (gcry_mpi_cmp(rsa_params[3], rsa_params[4]) > 0) { /* p, q = q, p */ gcry_mpi_swap(rsa_params[3], rsa_params[4]); /* due to swapping p and q, u = p^-1 mod p which happens to be needed. */ } /* libgcrypt expects u = p^-1 mod q (for OpenPGP), but the u parameter * says u = q^-1 mod p. Recompute u = p^-1 mod q. Do this unconditionally as * at least GnuTLS 2.12.23 computes an invalid value. */ gcry_mpi_invm(rsa_params[5], rsa_params[3], rsa_params[4]); if (gcry_sexp_build( &rsa_priv_key, NULL, "(private-key(rsa((n%m)(e%m)(d%m)(p%m)(q%m)(u%m))))", rsa_params[0], rsa_params[1], rsa_params[2], rsa_params[3], rsa_params[4], rsa_params[5]) != 0) { *err = g_strdup("can't build rsa private key s-exp"); return NULL; } for (i=0; i< 6; i++) gcry_mpi_release(rsa_params[i]); return rsa_priv_key; } gnutls_x509_privkey_t rsa_load_pem_key(FILE *fp, char **err) { /* gnutls makes our work much harder, since we have to work internally with * s-exp formatted data, but PEM loader exports only in "gnutls_datum_t" * format, and a datum -> s-exp conversion function does not exist. */ gnutls_x509_privkey_t priv_key; gnutls_datum_t key; ws_statb64 statbuf; gint ret; guint bytes; *err = NULL; if (ws_fstat64(ws_fileno(fp), &statbuf) == -1) { *err = ws_strdup_printf("can't ws_fstat64 file: %s", g_strerror(errno)); return NULL; } if (S_ISDIR(statbuf.st_mode)) { *err = g_strdup("file is a directory"); errno = EISDIR; return NULL; } if (S_ISFIFO(statbuf.st_mode)) { *err = g_strdup("file is a named pipe"); errno = EINVAL; return NULL; } if (!S_ISREG(statbuf.st_mode)) { *err = g_strdup("file is not a regular file"); errno = EINVAL; return NULL; } /* XXX - check for a too-big size */ /* load all file contents into a datum buffer*/ key.data = (unsigned char *)g_malloc((size_t)statbuf.st_size); key.size = (int)statbuf.st_size; bytes = (guint) fread(key.data, 1, key.size, fp); if (bytes < key.size) { if (bytes == 0 && ferror(fp)) { *err = ws_strdup_printf("can't read from file %d bytes, got error %s", key.size, g_strerror(errno)); } else { *err = ws_strdup_printf("can't read from file %d bytes, got %d", key.size, bytes); } g_free(key.data); return NULL; } /* init private key data*/ gnutls_x509_privkey_init(&priv_key); /* import PEM data*/ if ((ret = gnutls_x509_privkey_import(priv_key, &key, GNUTLS_X509_FMT_PEM)) != GNUTLS_E_SUCCESS) { *err = ws_strdup_printf("can't import pem data: %s", gnutls_strerror(ret)); g_free(key.data); gnutls_x509_privkey_deinit(priv_key); return NULL; } if (gnutls_x509_privkey_get_pk_algorithm(priv_key) != GNUTLS_PK_RSA) { *err = g_strdup("private key public key algorithm isn't RSA"); g_free(key.data); gnutls_x509_privkey_deinit(priv_key); return NULL; } g_free(key.data); return priv_key; } static const char * BAGTYPE(gnutls_pkcs12_bag_type_t x) { switch (x) { case GNUTLS_BAG_EMPTY: return "Empty"; case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY: return "PKCS#8 Encrypted key"; case GNUTLS_BAG_PKCS8_KEY: return "PKCS#8 Key"; case GNUTLS_BAG_CERTIFICATE: return "Certificate"; case GNUTLS_BAG_CRL: return "CRL"; case GNUTLS_BAG_ENCRYPTED: return "Encrypted"; case GNUTLS_BAG_UNKNOWN: return "Unknown"; default: return "<undefined>"; } } gnutls_x509_privkey_t rsa_load_pkcs12(FILE *fp, const gchar *cert_passwd, char **err) { int i, j, ret; int rest; unsigned char *p; gnutls_datum_t data; gnutls_pkcs12_bag_t bag = NULL; size_t len; gnutls_pkcs12_t rsa_p12 = NULL; gnutls_x509_privkey_t priv_key = NULL; *err = NULL; rest = 4096; data.data = (unsigned char *)g_malloc(rest); data.size = rest; p = data.data; while ((len = fread(p, 1, rest, fp)) > 0) { p += len; rest -= (int) len; if (!rest) { rest = 1024; data.data = (unsigned char *)g_realloc(data.data, data.size + rest); p = data.data + data.size; data.size += rest; } } data.size -= rest; if (!feof(fp)) { *err = g_strdup("Error during certificate reading."); g_free(data.data); return NULL; } ret = gnutls_pkcs12_init(&rsa_p12); if (ret < 0) { *err = ws_strdup_printf("gnutls_pkcs12_init(&st_p12) - %s", gnutls_strerror(ret)); g_free(data.data); return NULL; } /* load PKCS#12 in DER or PEM format */ ret = gnutls_pkcs12_import(rsa_p12, &data, GNUTLS_X509_FMT_DER, 0); if (ret < 0) { ret = gnutls_pkcs12_import(rsa_p12, &data, GNUTLS_X509_FMT_PEM, 0); if (ret < 0) { *err = ws_strdup_printf("could not load PKCS#12 in DER or PEM format: %s", gnutls_strerror(ret)); } } g_free(data.data); if (ret < 0) { gnutls_pkcs12_deinit(rsa_p12); return NULL; } ws_debug("grsa_privkey_to_sexp: PKCS#12 imported"); /* TODO: Use gnutls_pkcs12_simple_parse, since 3.1.0 (August 2012) */ for (i=0; ; i++) { gnutls_pkcs12_bag_type_t bag_type; ret = gnutls_pkcs12_bag_init(&bag); if (ret < 0) { *err = ws_strdup_printf("gnutls_pkcs12_bag_init failed: %s", gnutls_strerror(ret)); goto done; } ret = gnutls_pkcs12_get_bag(rsa_p12, i, bag); if (ret < 0) { *err = ws_strdup_printf("gnutls_pkcs12_get_bag failed: %s", gnutls_strerror(ret)); goto done; } for (j=0; j<gnutls_pkcs12_bag_get_count(bag); j++) { ret = gnutls_pkcs12_bag_get_type(bag, j); if (ret < 0) { *err = ws_strdup_printf("gnutls_pkcs12_bag_get_type failed: %s", gnutls_strerror(ret)); goto done; } bag_type = (gnutls_pkcs12_bag_type_t)ret; if (bag_type >= GNUTLS_BAG_UNKNOWN) { *err = ws_strdup_printf("gnutls_pkcs12_bag_get_type returned unknown bag type %u", ret); goto done; } ws_debug("Bag %d/%d: %s", i, j, BAGTYPE(bag_type)); if (bag_type == GNUTLS_BAG_ENCRYPTED) { ret = gnutls_pkcs12_bag_decrypt(bag, cert_passwd); if (ret == 0) { ret = gnutls_pkcs12_bag_get_type(bag, j); if (ret < 0) { *err = ws_strdup_printf("gnutls_pkcs12_bag_get_type failed: %s", gnutls_strerror(ret)); goto done; } bag_type = (gnutls_pkcs12_bag_type_t)ret; if (bag_type >= GNUTLS_BAG_UNKNOWN) { *err = ws_strdup_printf("gnutls_pkcs12_bag_get_type returned unknown bag type %u", ret); goto done; } ws_debug("Bag %d/%d decrypted: %s", i, j, BAGTYPE(bag_type)); } } ret = gnutls_pkcs12_bag_get_data(bag, j, &data); if (ret < 0) { *err = ws_strdup_printf("gnutls_pkcs12_bag_get_data failed: %s", gnutls_strerror(ret)); goto done; } switch (bag_type) { case GNUTLS_BAG_PKCS8_KEY: case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY: { gnutls_x509_privkey_t rsa_pkey; ret = gnutls_x509_privkey_init(&rsa_pkey); if (ret < 0) { *err = ws_strdup_printf("gnutls_x509_privkey_init failed: %s", gnutls_strerror(ret)); goto done; } ret = gnutls_x509_privkey_import_pkcs8(rsa_pkey, &data, GNUTLS_X509_FMT_DER, cert_passwd, (bag_type==GNUTLS_BAG_PKCS8_KEY) ? GNUTLS_PKCS_PLAIN : 0); if (ret < 0) { *err = ws_strdup_printf("Can not decrypt private key - %s", gnutls_strerror(ret)); gnutls_x509_privkey_deinit(rsa_pkey); goto done; } if (gnutls_x509_privkey_get_pk_algorithm(rsa_pkey) != GNUTLS_PK_RSA) { *err = g_strdup("private key public key algorithm isn't RSA"); gnutls_x509_privkey_deinit(rsa_pkey); goto done; } /* Private key found, return it. */ priv_key = rsa_pkey; goto done; } default: ; } } /* j */ gnutls_pkcs12_bag_deinit(bag); bag = NULL; } /* i */ done: if (bag) { gnutls_pkcs12_bag_deinit(bag); } if (!priv_key) { /* * We failed. If we didn't fail with an error, we failed because * we found no PKCS8 key and fell out of the loop; report that * error. */ if (*err == NULL) *err = g_strdup("no PKCS8 key found"); } gnutls_pkcs12_deinit(rsa_p12); return priv_key; } void rsa_private_key_free(gpointer key) { gcry_sexp_release((gcry_sexp_t) key); } #else /* ! defined(HAVE_LIBGNUTLS) */ void rsa_private_key_free(gpointer key _U_) { } #endif /* HAVE_LIBGNUTLS */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/rsa.h
/** @file * * Functions for RSA private key reading and use * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2007 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __RSA_H__ #define __RSA_H__ #include <wireshark.h> #include <gcrypt.h> #ifdef HAVE_LIBGNUTLS #include <stdio.h> #include <gnutls/abstract.h> WS_DLL_PUBLIC gcry_sexp_t rsa_privkey_to_sexp(gnutls_x509_privkey_t priv_key, char **err); /** * Load an RSA private key from specified file * @param fp the file that contain the key data * @param [out] err error message upon failure; NULL upon success * @return a pointer to the loaded key on success, or NULL upon failure */ WS_DLL_PUBLIC gnutls_x509_privkey_t rsa_load_pem_key(FILE* fp, char **err); /** * Load a RSA private key from a PKCS#12 file (DER or PEM format) * @param fp the file that contains the key data * @param cert_passwd password to decrypt the PKCS#12 file * @param [out] err error message upon failure; NULL upon success * @return a pointer to the loaded key on success; NULL upon failure */ WS_DLL_PUBLIC gnutls_x509_privkey_t rsa_load_pkcs12(FILE* fp, const char *cert_passwd, char** err); #endif WS_DLL_PUBLIC void rsa_private_key_free(gpointer key); #endif /* __RSA_H__ */
C/C++
wireshark/wsutil/safe-math.h
/* Overflow-safe math functions * Portable Snippets - https://github.com/nemequ/portable-snippets * Created by Evan Nemerson <[email protected]> * * To the extent possible under law, the authors have waived all * copyright and related or neighboring rights to this code. For * details, see the Creative Commons Zero 1.0 Universal license at * https://creativecommons.org/publicdomain/zero/1.0/ */ #if !defined(PSNIP_SAFE_H) #define PSNIP_SAFE_H #if !defined(PSNIP_SAFE_FORCE_PORTABLE) # if defined(__has_builtin) # if __has_builtin(__builtin_add_overflow) && !defined(__ibmxl__) # define PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW # endif # elif defined(__GNUC__) && (__GNUC__ >= 5) && !defined(__INTEL_COMPILER) # define PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW # endif # if defined(__has_include) # if __has_include(<intsafe.h>) # define PSNIP_SAFE_HAVE_INTSAFE_H # endif # elif defined(_WIN32) # define PSNIP_SAFE_HAVE_INTSAFE_H # endif #endif /* !defined(PSNIP_SAFE_FORCE_PORTABLE) */ #if defined(__GNUC__) # define PSNIP_SAFE_LIKELY(expr) __builtin_expect(!!(expr), 1) # define PSNIP_SAFE_UNLIKELY(expr) __builtin_expect(!!(expr), 0) #else # define PSNIP_SAFE_LIKELY(expr) !!(expr) # define PSNIP_SAFE_UNLIKELY(expr) !!(expr) #endif /* defined(__GNUC__) */ #if !defined(PSNIP_SAFE_STATIC_INLINE) # if defined(__GNUC__) # define PSNIP_SAFE__COMPILER_ATTRIBUTES __attribute__((__unused__)) # else # define PSNIP_SAFE__COMPILER_ATTRIBUTES # endif # if defined(HEDLEY_INLINE) # define PSNIP_SAFE__INLINE HEDLEY_INLINE # elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L # define PSNIP_SAFE__INLINE inline # elif defined(__GNUC_STDC_INLINE__) # define PSNIP_SAFE__INLINE __inline__ # elif defined(_MSC_VER) && _MSC_VER >= 1200 # define PSNIP_SAFE__INLINE __inline # else # define PSNIP_SAFE__INLINE # endif # define PSNIP_SAFE__FUNCTION PSNIP_SAFE__COMPILER_ATTRIBUTES static PSNIP_SAFE__INLINE #endif #if !defined(__cplusplus) && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L # define psnip_safe_bool _Bool #else # define psnip_safe_bool int #endif #if !defined(PSNIP_SAFE_NO_FIXED) /* For maximum portability include the exact-int module from portable snippets. */ # if \ !defined(psnip_int64_t) || !defined(psnip_uint64_t) || \ !defined(psnip_int32_t) || !defined(psnip_uint32_t) || \ !defined(psnip_int16_t) || !defined(psnip_uint16_t) || \ !defined(psnip_int8_t) || !defined(psnip_uint8_t) # include <stdint.h> # if !defined(psnip_int64_t) # define psnip_int64_t int64_t # endif # if !defined(psnip_uint64_t) # define psnip_uint64_t uint64_t # endif # if !defined(psnip_int32_t) # define psnip_int32_t int32_t # endif # if !defined(psnip_uint32_t) # define psnip_uint32_t uint32_t # endif # if !defined(psnip_int16_t) # define psnip_int16_t int16_t # endif # if !defined(psnip_uint16_t) # define psnip_uint16_t uint16_t # endif # if !defined(psnip_int8_t) # define psnip_int8_t int8_t # endif # if !defined(psnip_uint8_t) # define psnip_uint8_t uint8_t # endif # endif #endif /* !defined(PSNIP_SAFE_NO_FIXED) */ #include <limits.h> #include <stdlib.h> #if !defined(PSNIP_SAFE_SIZE_MAX) # if defined(__SIZE_MAX__) # define PSNIP_SAFE_SIZE_MAX __SIZE_MAX__ # elif defined(PSNIP_EXACT_INT_HAVE_STDINT) # include <stdint.h> # endif #endif #if defined(PSNIP_SAFE_SIZE_MAX) # define PSNIP_SAFE__SIZE_MAX_RT PSNIP_SAFE_SIZE_MAX #else # define PSNIP_SAFE__SIZE_MAX_RT (~((size_t) 0)) #endif #if defined(PSNIP_SAFE_HAVE_INTSAFE_H) /* In VS 10, stdint.h and intsafe.h both define (U)INTN_MIN/MAX, which triggers warning C4005 (level 1). */ # if defined(_MSC_VER) && (_MSC_VER == 1600) # pragma warning(push) # pragma warning(disable:4005) # endif # include <intsafe.h> # if defined(_MSC_VER) && (_MSC_VER == 1600) # pragma warning(pop) # endif #endif /* defined(PSNIP_SAFE_HAVE_INTSAFE_H) */ /* If there is a type larger than the one we're concerned with it's * likely much faster to simply promote the operands, perform the * requested operation, verify that the result falls within the * original type, then cast the result back to the original type. */ #if !defined(PSNIP_SAFE_NO_PROMOTIONS) #define PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, op_name, op) \ PSNIP_SAFE__FUNCTION psnip_safe_##name##_larger \ psnip_safe_larger_##name##_##op_name (T a, T b) { \ return ((psnip_safe_##name##_larger) a) op ((psnip_safe_##name##_larger) b); \ } #define PSNIP_SAFE_DEFINE_LARGER_UNARY_OP(T, name, op_name, op) \ PSNIP_SAFE__FUNCTION psnip_safe_##name##_larger \ psnip_safe_larger_##name##_##op_name (T value) { \ return (op ((psnip_safe_##name##_larger) value)); \ } #define PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(T, name) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, add, +) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, sub, -) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, mul, *) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, div, /) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, mod, %) \ PSNIP_SAFE_DEFINE_LARGER_UNARY_OP (T, name, neg, -) #define PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(T, name) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, add, +) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, sub, -) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, mul, *) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, div, /) \ PSNIP_SAFE_DEFINE_LARGER_BINARY_OP(T, name, mod, %) #define PSNIP_SAFE_IS_LARGER(ORIG_MAX, DEST_MAX) ((DEST_MAX / ORIG_MAX) >= ORIG_MAX) #if defined(__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__SIZEOF_INT128__) && !defined(__ibmxl__) #define PSNIP_SAFE_HAVE_128 typedef __int128 psnip_safe_int128_t; typedef unsigned __int128 psnip_safe_uint128_t; #endif /* defined(__GNUC__) */ #if !defined(PSNIP_SAFE_NO_FIXED) #define PSNIP_SAFE_HAVE_INT8_LARGER #define PSNIP_SAFE_HAVE_UINT8_LARGER typedef psnip_int16_t psnip_safe_int8_larger; typedef psnip_uint16_t psnip_safe_uint8_larger; #define PSNIP_SAFE_HAVE_INT16_LARGER typedef psnip_int32_t psnip_safe_int16_larger; typedef psnip_uint32_t psnip_safe_uint16_larger; #define PSNIP_SAFE_HAVE_INT32_LARGER typedef psnip_int64_t psnip_safe_int32_larger; typedef psnip_uint64_t psnip_safe_uint32_larger; #if defined(PSNIP_SAFE_HAVE_128) #define PSNIP_SAFE_HAVE_INT64_LARGER typedef psnip_safe_int128_t psnip_safe_int64_larger; typedef psnip_safe_uint128_t psnip_safe_uint64_larger; #endif /* defined(PSNIP_SAFE_HAVE_128) */ #endif /* !defined(PSNIP_SAFE_NO_FIXED) */ #define PSNIP_SAFE_HAVE_LARGER_SCHAR #if PSNIP_SAFE_IS_LARGER(SCHAR_MAX, SHRT_MAX) typedef short psnip_safe_schar_larger; #elif PSNIP_SAFE_IS_LARGER(SCHAR_MAX, INT_MAX) typedef int psnip_safe_schar_larger; #elif PSNIP_SAFE_IS_LARGER(SCHAR_MAX, LONG_MAX) typedef long psnip_safe_schar_larger; #elif PSNIP_SAFE_IS_LARGER(SCHAR_MAX, LLONG_MAX) typedef long long psnip_safe_schar_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(SCHAR_MAX, 0x7fff) typedef psnip_int16_t psnip_safe_schar_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(SCHAR_MAX, 0x7fffffffLL) typedef psnip_int32_t psnip_safe_schar_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(SCHAR_MAX, 0x7fffffffffffffffLL) typedef psnip_int64_t psnip_safe_schar_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (SCHAR_MAX <= 0x7fffffffffffffffLL) typedef psnip_safe_int128_t psnip_safe_schar_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_SCHAR #endif #define PSNIP_SAFE_HAVE_LARGER_UCHAR #if PSNIP_SAFE_IS_LARGER(UCHAR_MAX, USHRT_MAX) typedef unsigned short psnip_safe_uchar_larger; #elif PSNIP_SAFE_IS_LARGER(UCHAR_MAX, UINT_MAX) typedef unsigned int psnip_safe_uchar_larger; #elif PSNIP_SAFE_IS_LARGER(UCHAR_MAX, ULONG_MAX) typedef unsigned long psnip_safe_uchar_larger; #elif PSNIP_SAFE_IS_LARGER(UCHAR_MAX, ULLONG_MAX) typedef unsigned long long psnip_safe_uchar_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(UCHAR_MAX, 0xffffU) typedef psnip_uint16_t psnip_safe_uchar_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(UCHAR_MAX, 0xffffffffUL) typedef psnip_uint32_t psnip_safe_uchar_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(UCHAR_MAX, 0xffffffffffffffffULL) typedef psnip_uint64_t psnip_safe_uchar_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (UCHAR_MAX <= 0xffffffffffffffffULL) typedef psnip_safe_uint128_t psnip_safe_uchar_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_UCHAR #endif #if CHAR_MIN == 0 && defined(PSNIP_SAFE_HAVE_LARGER_UCHAR) #define PSNIP_SAFE_HAVE_LARGER_CHAR typedef psnip_safe_uchar_larger psnip_safe_char_larger; #elif CHAR_MIN < 0 && defined(PSNIP_SAFE_HAVE_LARGER_SCHAR) #define PSNIP_SAFE_HAVE_LARGER_CHAR typedef psnip_safe_schar_larger psnip_safe_char_larger; #endif #define PSNIP_SAFE_HAVE_LARGER_SHRT #if PSNIP_SAFE_IS_LARGER(SHRT_MAX, INT_MAX) typedef int psnip_safe_short_larger; #elif PSNIP_SAFE_IS_LARGER(SHRT_MAX, LONG_MAX) typedef long psnip_safe_short_larger; #elif PSNIP_SAFE_IS_LARGER(SHRT_MAX, LLONG_MAX) typedef long long psnip_safe_short_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(SHRT_MAX, 0x7fff) typedef psnip_int16_t psnip_safe_short_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(SHRT_MAX, 0x7fffffffLL) typedef psnip_int32_t psnip_safe_short_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(SHRT_MAX, 0x7fffffffffffffffLL) typedef psnip_int64_t psnip_safe_short_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (SHRT_MAX <= 0x7fffffffffffffffLL) typedef psnip_safe_int128_t psnip_safe_short_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_SHRT #endif #define PSNIP_SAFE_HAVE_LARGER_USHRT #if PSNIP_SAFE_IS_LARGER(USHRT_MAX, UINT_MAX) typedef unsigned int psnip_safe_ushort_larger; #elif PSNIP_SAFE_IS_LARGER(USHRT_MAX, ULONG_MAX) typedef unsigned long psnip_safe_ushort_larger; #elif PSNIP_SAFE_IS_LARGER(USHRT_MAX, ULLONG_MAX) typedef unsigned long long psnip_safe_ushort_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(USHRT_MAX, 0xffff) typedef psnip_uint16_t psnip_safe_ushort_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(USHRT_MAX, 0xffffffffUL) typedef psnip_uint32_t psnip_safe_ushort_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(USHRT_MAX, 0xffffffffffffffffULL) typedef psnip_uint64_t psnip_safe_ushort_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (USHRT_MAX <= 0xffffffffffffffffULL) typedef psnip_safe_uint128_t psnip_safe_ushort_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_USHRT #endif #define PSNIP_SAFE_HAVE_LARGER_INT #if PSNIP_SAFE_IS_LARGER(INT_MAX, LONG_MAX) typedef long psnip_safe_int_larger; #elif PSNIP_SAFE_IS_LARGER(INT_MAX, LLONG_MAX) typedef long long psnip_safe_int_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(INT_MAX, 0x7fff) typedef psnip_int16_t psnip_safe_int_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(INT_MAX, 0x7fffffffLL) typedef psnip_int32_t psnip_safe_int_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(INT_MAX, 0x7fffffffffffffffLL) typedef psnip_int64_t psnip_safe_int_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (INT_MAX <= 0x7fffffffffffffffLL) typedef psnip_safe_int128_t psnip_safe_int_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_INT #endif #define PSNIP_SAFE_HAVE_LARGER_UINT #if PSNIP_SAFE_IS_LARGER(UINT_MAX, ULONG_MAX) typedef unsigned long psnip_safe_uint_larger; #elif PSNIP_SAFE_IS_LARGER(UINT_MAX, ULLONG_MAX) typedef unsigned long long psnip_safe_uint_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(UINT_MAX, 0xffff) typedef psnip_uint16_t psnip_safe_uint_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(UINT_MAX, 0xffffffffUL) typedef psnip_uint32_t psnip_safe_uint_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(UINT_MAX, 0xffffffffffffffffULL) typedef psnip_uint64_t psnip_safe_uint_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (UINT_MAX <= 0xffffffffffffffffULL) typedef psnip_safe_uint128_t psnip_safe_uint_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_UINT #endif #define PSNIP_SAFE_HAVE_LARGER_LONG #if PSNIP_SAFE_IS_LARGER(LONG_MAX, LLONG_MAX) typedef long long psnip_safe_long_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(LONG_MAX, 0x7fff) typedef psnip_int16_t psnip_safe_long_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(LONG_MAX, 0x7fffffffLL) typedef psnip_int32_t psnip_safe_long_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(LONG_MAX, 0x7fffffffffffffffLL) typedef psnip_int64_t psnip_safe_long_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (LONG_MAX <= 0x7fffffffffffffffLL) typedef psnip_safe_int128_t psnip_safe_long_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_LONG #endif #define PSNIP_SAFE_HAVE_LARGER_ULONG #if PSNIP_SAFE_IS_LARGER(ULONG_MAX, ULLONG_MAX) typedef unsigned long long psnip_safe_ulong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(ULONG_MAX, 0xffff) typedef psnip_uint16_t psnip_safe_ulong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(ULONG_MAX, 0xffffffffUL) typedef psnip_uint32_t psnip_safe_ulong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(ULONG_MAX, 0xffffffffffffffffULL) typedef psnip_uint64_t psnip_safe_ulong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (ULONG_MAX <= 0xffffffffffffffffULL) typedef psnip_safe_uint128_t psnip_safe_ulong_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_ULONG #endif #define PSNIP_SAFE_HAVE_LARGER_LLONG #if !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(LLONG_MAX, 0x7fff) typedef psnip_int16_t psnip_safe_llong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(LLONG_MAX, 0x7fffffffLL) typedef psnip_int32_t psnip_safe_llong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(LLONG_MAX, 0x7fffffffffffffffLL) typedef psnip_int64_t psnip_safe_llong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (LLONG_MAX <= 0x7fffffffffffffffLL) typedef psnip_safe_int128_t psnip_safe_llong_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_LLONG #endif #define PSNIP_SAFE_HAVE_LARGER_ULLONG #if !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(ULLONG_MAX, 0xffff) typedef psnip_uint16_t psnip_safe_ullong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(ULLONG_MAX, 0xffffffffUL) typedef psnip_uint32_t psnip_safe_ullong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(ULLONG_MAX, 0xffffffffffffffffULL) typedef psnip_uint64_t psnip_safe_ullong_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (ULLONG_MAX <= 0xffffffffffffffffULL) typedef psnip_safe_uint128_t psnip_safe_ullong_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_ULLONG #endif #if defined(PSNIP_SAFE_SIZE_MAX) #define PSNIP_SAFE_HAVE_LARGER_SIZE #if PSNIP_SAFE_IS_LARGER(PSNIP_SAFE_SIZE_MAX, USHRT_MAX) typedef unsigned short psnip_safe_size_larger; #elif PSNIP_SAFE_IS_LARGER(PSNIP_SAFE_SIZE_MAX, UINT_MAX) typedef unsigned int psnip_safe_size_larger; #elif PSNIP_SAFE_IS_LARGER(PSNIP_SAFE_SIZE_MAX, ULONG_MAX) typedef unsigned long psnip_safe_size_larger; #elif PSNIP_SAFE_IS_LARGER(PSNIP_SAFE_SIZE_MAX, ULLONG_MAX) typedef unsigned long long psnip_safe_size_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(PSNIP_SAFE_SIZE_MAX, 0xffff) typedef psnip_uint16_t psnip_safe_size_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(PSNIP_SAFE_SIZE_MAX, 0xffffffffUL) typedef psnip_uint32_t psnip_safe_size_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && PSNIP_SAFE_IS_LARGER(PSNIP_SAFE_SIZE_MAX, 0xffffffffffffffffULL) typedef psnip_uint64_t psnip_safe_size_larger; #elif !defined(PSNIP_SAFE_NO_FIXED) && defined(PSNIP_SAFE_HAVE_128) && (PSNIP_SAFE_SIZE_MAX <= 0xffffffffffffffffULL) typedef psnip_safe_uint128_t psnip_safe_size_larger; #else #undef PSNIP_SAFE_HAVE_LARGER_SIZE #endif #endif #if defined(PSNIP_SAFE_HAVE_LARGER_SCHAR) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(signed char, schar) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_UCHAR) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(unsigned char, uchar) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_CHAR) #if CHAR_MIN == 0 PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(char, char) #else PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(char, char) #endif #endif #if defined(PSNIP_SAFE_HAVE_LARGER_SHORT) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(short, short) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_USHORT) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(unsigned short, ushort) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_INT) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(int, int) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_UINT) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(unsigned int, uint) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_LONG) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(long, long) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_ULONG) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(unsigned long, ulong) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_LLONG) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(long long, llong) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_ULLONG) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(unsigned long long, ullong) #endif #if defined(PSNIP_SAFE_HAVE_LARGER_SIZE) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(size_t, size) #endif #if !defined(PSNIP_SAFE_NO_FIXED) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(psnip_int8_t, int8) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(psnip_uint8_t, uint8) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(psnip_int16_t, int16) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(psnip_uint16_t, uint16) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(psnip_int32_t, int32) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(psnip_uint32_t, uint32) #if defined(PSNIP_SAFE_HAVE_128) PSNIP_SAFE_DEFINE_LARGER_SIGNED_OPS(psnip_int64_t, int64) PSNIP_SAFE_DEFINE_LARGER_UNSIGNED_OPS(psnip_uint64_t, uint64) #endif #endif #endif /* !defined(PSNIP_SAFE_NO_PROMOTIONS) */ #define PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(T, name, op_name) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_##op_name(T* res, T a, T b) { \ return !__builtin_##op_name##_overflow(a, b, res); \ } #define PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(T, name, op_name, min, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_##op_name(T* res, T a, T b) { \ const psnip_safe_##name##_larger r = psnip_safe_larger_##name##_##op_name(a, b); \ *res = (T) r; \ return (r >= min) && (r <= max); \ } #define PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(T, name, op_name, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_##op_name(T* res, T a, T b) { \ const psnip_safe_##name##_larger r = psnip_safe_larger_##name##_##op_name(a, b); \ *res = (T) r; \ return (r <= max); \ } #define PSNIP_SAFE_DEFINE_SIGNED_ADD(T, name, min, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_add (T* res, T a, T b) { \ psnip_safe_bool r = !( ((b > 0) && (a > (max - b))) || \ ((b < 0) && (a < (min - b))) ); \ if(PSNIP_SAFE_LIKELY(r)) \ *res = a + b; \ return r; \ } #define PSNIP_SAFE_DEFINE_UNSIGNED_ADD(T, name, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_add (T* res, T a, T b) { \ *res = (T) (a + b); \ return !PSNIP_SAFE_UNLIKELY((b > 0) && (a > (max - b))); \ } #define PSNIP_SAFE_DEFINE_SIGNED_SUB(T, name, min, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_sub (T* res, T a, T b) { \ psnip_safe_bool r = !((b > 0 && a < (min + b)) || \ (b < 0 && a > (max + b))); \ if(PSNIP_SAFE_LIKELY(r)) \ *res = a - b; \ return r; \ } #define PSNIP_SAFE_DEFINE_UNSIGNED_SUB(T, name, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_sub (T* res, T a, T b) { \ *res = a - b; \ return !PSNIP_SAFE_UNLIKELY(b > a); \ } #define PSNIP_SAFE_DEFINE_SIGNED_MUL(T, name, min, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_mul (T* res, T a, T b) { \ psnip_safe_bool r = 1; \ if (a > 0) { \ if (b > 0) { \ if (a > (max / b)) { \ r = 0; \ } \ } else { \ if (b < (min / a)) { \ r = 0; \ } \ } \ } else { \ if (b > 0) { \ if (a < (min / b)) { \ r = 0; \ } \ } else { \ if ( (a != 0) && (b < (max / a))) { \ r = 0; \ } \ } \ } \ if(PSNIP_SAFE_LIKELY(r)) \ *res = a * b; \ return r; \ } #define PSNIP_SAFE_DEFINE_UNSIGNED_MUL(T, name, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_mul (T* res, T a, T b) { \ *res = (T) (a * b); \ return !PSNIP_SAFE_UNLIKELY((a > 0) && (b > 0) && (a > (max / b))); \ } #define PSNIP_SAFE_DEFINE_SIGNED_DIV(T, name, min, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_div (T* res, T a, T b) { \ if (PSNIP_SAFE_UNLIKELY(b == 0)) { \ *res = 0; \ return 0; \ } else if (PSNIP_SAFE_UNLIKELY(a == min && b == -1)) { \ *res = min; \ return 0; \ } else { \ *res = (T) (a / b); \ return 1; \ } \ } #define PSNIP_SAFE_DEFINE_UNSIGNED_DIV(T, name, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_div (T* res, T a, T b) { \ if (PSNIP_SAFE_UNLIKELY(b == 0)) { \ *res = 0; \ return 0; \ } else { \ *res = a / b; \ return 1; \ } \ } #define PSNIP_SAFE_DEFINE_SIGNED_MOD(T, name, min, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_mod (T* res, T a, T b) { \ if (PSNIP_SAFE_UNLIKELY(b == 0)) { \ *res = 0; \ return 0; \ } else if (PSNIP_SAFE_UNLIKELY(a == min && b == -1)) { \ *res = min; \ return 0; \ } else { \ *res = (T) (a % b); \ return 1; \ } \ } #define PSNIP_SAFE_DEFINE_UNSIGNED_MOD(T, name, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_mod (T* res, T a, T b) { \ if (PSNIP_SAFE_UNLIKELY(b == 0)) { \ *res = 0; \ return 0; \ } else { \ *res = a % b; \ return 1; \ } \ } #define PSNIP_SAFE_DEFINE_SIGNED_NEG(T, name, min, max) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_neg (T* res, T value) { \ psnip_safe_bool r = value != min; \ *res = PSNIP_SAFE_LIKELY(r) ? -value : max; \ return r; \ } #define PSNIP_SAFE_DEFINE_INTSAFE(T, name, op, isf) \ PSNIP_SAFE__FUNCTION psnip_safe_bool \ psnip_safe_##name##_##op (T* res, T a, T b) { \ return isf(a, b, res) == S_OK; \ } #if CHAR_MIN == 0 #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(char, char, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(char, char, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(char, char, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_CHAR) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(char, char, add, CHAR_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(char, char, sub, CHAR_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(char, char, mul, CHAR_MAX) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(char, char, CHAR_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(char, char, CHAR_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(char, char, CHAR_MAX) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(char, char, CHAR_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(char, char, CHAR_MAX) #else /* CHAR_MIN != 0 */ #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(char, char, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(char, char, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(char, char, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_CHAR) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(char, char, add, CHAR_MIN, CHAR_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(char, char, sub, CHAR_MIN, CHAR_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(char, char, mul, CHAR_MIN, CHAR_MAX) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(char, char, CHAR_MIN, CHAR_MAX) PSNIP_SAFE_DEFINE_SIGNED_SUB(char, char, CHAR_MIN, CHAR_MAX) PSNIP_SAFE_DEFINE_SIGNED_MUL(char, char, CHAR_MIN, CHAR_MAX) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(char, char, CHAR_MIN, CHAR_MAX) PSNIP_SAFE_DEFINE_SIGNED_MOD(char, char, CHAR_MIN, CHAR_MAX) PSNIP_SAFE_DEFINE_SIGNED_NEG(char, char, CHAR_MIN, CHAR_MAX) #endif #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(signed char, schar, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(signed char, schar, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(signed char, schar, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_SCHAR) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(signed char, schar, add, SCHAR_MIN, SCHAR_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(signed char, schar, sub, SCHAR_MIN, SCHAR_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(signed char, schar, mul, SCHAR_MIN, SCHAR_MAX) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(signed char, schar, SCHAR_MIN, SCHAR_MAX) PSNIP_SAFE_DEFINE_SIGNED_SUB(signed char, schar, SCHAR_MIN, SCHAR_MAX) PSNIP_SAFE_DEFINE_SIGNED_MUL(signed char, schar, SCHAR_MIN, SCHAR_MAX) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(signed char, schar, SCHAR_MIN, SCHAR_MAX) PSNIP_SAFE_DEFINE_SIGNED_MOD(signed char, schar, SCHAR_MIN, SCHAR_MAX) PSNIP_SAFE_DEFINE_SIGNED_NEG(signed char, schar, SCHAR_MIN, SCHAR_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned char, uchar, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned char, uchar, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned char, uchar, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_UCHAR) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned char, uchar, add, UCHAR_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned char, uchar, sub, UCHAR_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned char, uchar, mul, UCHAR_MAX) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(unsigned char, uchar, UCHAR_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(unsigned char, uchar, UCHAR_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(unsigned char, uchar, UCHAR_MAX) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(unsigned char, uchar, UCHAR_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(unsigned char, uchar, UCHAR_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(short, short, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(short, short, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(short, short, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_SHORT) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(short, short, add, SHRT_MIN, SHRT_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(short, short, sub, SHRT_MIN, SHRT_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(short, short, mul, SHRT_MIN, SHRT_MAX) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(short, short, SHRT_MIN, SHRT_MAX) PSNIP_SAFE_DEFINE_SIGNED_SUB(short, short, SHRT_MIN, SHRT_MAX) PSNIP_SAFE_DEFINE_SIGNED_MUL(short, short, SHRT_MIN, SHRT_MAX) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(short, short, SHRT_MIN, SHRT_MAX) PSNIP_SAFE_DEFINE_SIGNED_MOD(short, short, SHRT_MIN, SHRT_MAX) PSNIP_SAFE_DEFINE_SIGNED_NEG(short, short, SHRT_MIN, SHRT_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned short, ushort, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned short, ushort, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned short, ushort, mul) #elif defined(PSNIP_SAFE_HAVE_INTSAFE_H) PSNIP_SAFE_DEFINE_INTSAFE(unsigned short, ushort, add, UShortAdd) PSNIP_SAFE_DEFINE_INTSAFE(unsigned short, ushort, sub, UShortSub) PSNIP_SAFE_DEFINE_INTSAFE(unsigned short, ushort, mul, UShortMult) #elif defined(PSNIP_SAFE_HAVE_LARGER_USHORT) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned short, ushort, add, USHRT_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned short, ushort, sub, USHRT_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned short, ushort, mul, USHRT_MAX) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(unsigned short, ushort, USHRT_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(unsigned short, ushort, USHRT_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(unsigned short, ushort, USHRT_MAX) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(unsigned short, ushort, USHRT_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(unsigned short, ushort, USHRT_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(int, int, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(int, int, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(int, int, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_INT) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(int, int, add, INT_MIN, INT_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(int, int, sub, INT_MIN, INT_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(int, int, mul, INT_MIN, INT_MAX) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(int, int, INT_MIN, INT_MAX) PSNIP_SAFE_DEFINE_SIGNED_SUB(int, int, INT_MIN, INT_MAX) PSNIP_SAFE_DEFINE_SIGNED_MUL(int, int, INT_MIN, INT_MAX) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(int, int, INT_MIN, INT_MAX) PSNIP_SAFE_DEFINE_SIGNED_MOD(int, int, INT_MIN, INT_MAX) PSNIP_SAFE_DEFINE_SIGNED_NEG(int, int, INT_MIN, INT_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned int, uint, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned int, uint, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned int, uint, mul) #elif defined(PSNIP_SAFE_HAVE_INTSAFE_H) PSNIP_SAFE_DEFINE_INTSAFE(unsigned int, uint, add, UIntAdd) PSNIP_SAFE_DEFINE_INTSAFE(unsigned int, uint, sub, UIntSub) PSNIP_SAFE_DEFINE_INTSAFE(unsigned int, uint, mul, UIntMult) #elif defined(PSNIP_SAFE_HAVE_LARGER_UINT) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned int, uint, add, UINT_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned int, uint, sub, UINT_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned int, uint, mul, UINT_MAX) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(unsigned int, uint, UINT_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(unsigned int, uint, UINT_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(unsigned int, uint, UINT_MAX) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(unsigned int, uint, UINT_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(unsigned int, uint, UINT_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(long, long, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(long, long, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(long, long, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_LONG) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(long, long, add, LONG_MIN, LONG_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(long, long, sub, LONG_MIN, LONG_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(long, long, mul, LONG_MIN, LONG_MAX) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(long, long, LONG_MIN, LONG_MAX) PSNIP_SAFE_DEFINE_SIGNED_SUB(long, long, LONG_MIN, LONG_MAX) PSNIP_SAFE_DEFINE_SIGNED_MUL(long, long, LONG_MIN, LONG_MAX) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(long, long, LONG_MIN, LONG_MAX) PSNIP_SAFE_DEFINE_SIGNED_MOD(long, long, LONG_MIN, LONG_MAX) PSNIP_SAFE_DEFINE_SIGNED_NEG(long, long, LONG_MIN, LONG_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned long, ulong, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned long, ulong, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned long, ulong, mul) #elif defined(PSNIP_SAFE_HAVE_INTSAFE_H) PSNIP_SAFE_DEFINE_INTSAFE(unsigned long, ulong, add, ULongAdd) PSNIP_SAFE_DEFINE_INTSAFE(unsigned long, ulong, sub, ULongSub) PSNIP_SAFE_DEFINE_INTSAFE(unsigned long, ulong, mul, ULongMult) #elif defined(PSNIP_SAFE_HAVE_LARGER_ULONG) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned long, ulong, add, ULONG_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned long, ulong, sub, ULONG_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned long, ulong, mul, ULONG_MAX) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(unsigned long, ulong, ULONG_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(unsigned long, ulong, ULONG_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(unsigned long, ulong, ULONG_MAX) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(unsigned long, ulong, ULONG_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(unsigned long, ulong, ULONG_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(long long, llong, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(long long, llong, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(long long, llong, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_LLONG) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(long long, llong, add, LLONG_MIN, LLONG_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(long long, llong, sub, LLONG_MIN, LLONG_MAX) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(long long, llong, mul, LLONG_MIN, LLONG_MAX) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(long long, llong, LLONG_MIN, LLONG_MAX) PSNIP_SAFE_DEFINE_SIGNED_SUB(long long, llong, LLONG_MIN, LLONG_MAX) PSNIP_SAFE_DEFINE_SIGNED_MUL(long long, llong, LLONG_MIN, LLONG_MAX) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(long long, llong, LLONG_MIN, LLONG_MAX) PSNIP_SAFE_DEFINE_SIGNED_MOD(long long, llong, LLONG_MIN, LLONG_MAX) PSNIP_SAFE_DEFINE_SIGNED_NEG(long long, llong, LLONG_MIN, LLONG_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned long long, ullong, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned long long, ullong, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(unsigned long long, ullong, mul) #elif defined(PSNIP_SAFE_HAVE_INTSAFE_H) PSNIP_SAFE_DEFINE_INTSAFE(unsigned long long, ullong, add, ULongLongAdd) PSNIP_SAFE_DEFINE_INTSAFE(unsigned long long, ullong, sub, ULongLongSub) PSNIP_SAFE_DEFINE_INTSAFE(unsigned long long, ullong, mul, ULongLongMult) #elif defined(PSNIP_SAFE_HAVE_LARGER_ULLONG) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned long long, ullong, add, ULLONG_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned long long, ullong, sub, ULLONG_MAX) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(unsigned long long, ullong, mul, ULLONG_MAX) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(unsigned long long, ullong, ULLONG_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(unsigned long long, ullong, ULLONG_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(unsigned long long, ullong, ULLONG_MAX) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(unsigned long long, ullong, ULLONG_MAX) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(unsigned long long, ullong, ULLONG_MAX) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(size_t, size, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(size_t, size, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(size_t, size, mul) #elif defined(PSNIP_SAFE_HAVE_INTSAFE_H) PSNIP_SAFE_DEFINE_INTSAFE(size_t, size, add, SizeTAdd) PSNIP_SAFE_DEFINE_INTSAFE(size_t, size, sub, SizeTSub) PSNIP_SAFE_DEFINE_INTSAFE(size_t, size, mul, SizeTMult) #elif defined(PSNIP_SAFE_HAVE_LARGER_SIZE) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(size_t, size, add, PSNIP_SAFE__SIZE_MAX_RT) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(size_t, size, sub, PSNIP_SAFE__SIZE_MAX_RT) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(size_t, size, mul, PSNIP_SAFE__SIZE_MAX_RT) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(size_t, size, PSNIP_SAFE__SIZE_MAX_RT) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(size_t, size, PSNIP_SAFE__SIZE_MAX_RT) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(size_t, size, PSNIP_SAFE__SIZE_MAX_RT) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(size_t, size, PSNIP_SAFE__SIZE_MAX_RT) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(size_t, size, PSNIP_SAFE__SIZE_MAX_RT) #if !defined(PSNIP_SAFE_NO_FIXED) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int8_t, int8, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int8_t, int8, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int8_t, int8, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_INT8) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int8_t, int8, add, (-0x7fLL-1), 0x7f) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int8_t, int8, sub, (-0x7fLL-1), 0x7f) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int8_t, int8, mul, (-0x7fLL-1), 0x7f) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(psnip_int8_t, int8, (-0x7fLL-1), 0x7f) PSNIP_SAFE_DEFINE_SIGNED_SUB(psnip_int8_t, int8, (-0x7fLL-1), 0x7f) PSNIP_SAFE_DEFINE_SIGNED_MUL(psnip_int8_t, int8, (-0x7fLL-1), 0x7f) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(psnip_int8_t, int8, (-0x7fLL-1), 0x7f) PSNIP_SAFE_DEFINE_SIGNED_MOD(psnip_int8_t, int8, (-0x7fLL-1), 0x7f) PSNIP_SAFE_DEFINE_SIGNED_NEG(psnip_int8_t, int8, (-0x7fLL-1), 0x7f) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint8_t, uint8, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint8_t, uint8, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint8_t, uint8, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_UINT8) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint8_t, uint8, add, 0xff) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint8_t, uint8, sub, 0xff) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint8_t, uint8, mul, 0xff) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(psnip_uint8_t, uint8, 0xff) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(psnip_uint8_t, uint8, 0xff) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(psnip_uint8_t, uint8, 0xff) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(psnip_uint8_t, uint8, 0xff) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(psnip_uint8_t, uint8, 0xff) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int16_t, int16, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int16_t, int16, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int16_t, int16, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_INT16) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int16_t, int16, add, (-32767-1), 0x7fff) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int16_t, int16, sub, (-32767-1), 0x7fff) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int16_t, int16, mul, (-32767-1), 0x7fff) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(psnip_int16_t, int16, (-32767-1), 0x7fff) PSNIP_SAFE_DEFINE_SIGNED_SUB(psnip_int16_t, int16, (-32767-1), 0x7fff) PSNIP_SAFE_DEFINE_SIGNED_MUL(psnip_int16_t, int16, (-32767-1), 0x7fff) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(psnip_int16_t, int16, (-32767-1), 0x7fff) PSNIP_SAFE_DEFINE_SIGNED_MOD(psnip_int16_t, int16, (-32767-1), 0x7fff) PSNIP_SAFE_DEFINE_SIGNED_NEG(psnip_int16_t, int16, (-32767-1), 0x7fff) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint16_t, uint16, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint16_t, uint16, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint16_t, uint16, mul) #elif defined(PSNIP_SAFE_HAVE_INTSAFE_H) && defined(_WIN32) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint16_t, uint16, add, UShortAdd) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint16_t, uint16, sub, UShortSub) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint16_t, uint16, mul, UShortMult) #elif defined(PSNIP_SAFE_HAVE_LARGER_UINT16) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint16_t, uint16, add, 0xffff) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint16_t, uint16, sub, 0xffff) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint16_t, uint16, mul, 0xffff) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(psnip_uint16_t, uint16, 0xffff) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(psnip_uint16_t, uint16, 0xffff) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(psnip_uint16_t, uint16, 0xffff) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(psnip_uint16_t, uint16, 0xffff) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(psnip_uint16_t, uint16, 0xffff) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int32_t, int32, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int32_t, int32, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int32_t, int32, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_INT32) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int32_t, int32, add, (-0x7fffffffLL-1), 0x7fffffffLL) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int32_t, int32, sub, (-0x7fffffffLL-1), 0x7fffffffLL) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int32_t, int32, mul, (-0x7fffffffLL-1), 0x7fffffffLL) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(psnip_int32_t, int32, (-0x7fffffffLL-1), 0x7fffffffLL) PSNIP_SAFE_DEFINE_SIGNED_SUB(psnip_int32_t, int32, (-0x7fffffffLL-1), 0x7fffffffLL) PSNIP_SAFE_DEFINE_SIGNED_MUL(psnip_int32_t, int32, (-0x7fffffffLL-1), 0x7fffffffLL) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(psnip_int32_t, int32, (-0x7fffffffLL-1), 0x7fffffffLL) PSNIP_SAFE_DEFINE_SIGNED_MOD(psnip_int32_t, int32, (-0x7fffffffLL-1), 0x7fffffffLL) PSNIP_SAFE_DEFINE_SIGNED_NEG(psnip_int32_t, int32, (-0x7fffffffLL-1), 0x7fffffffLL) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint32_t, uint32, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint32_t, uint32, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint32_t, uint32, mul) #elif defined(PSNIP_SAFE_HAVE_INTSAFE_H) && defined(_WIN32) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint32_t, uint32, add, UIntAdd) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint32_t, uint32, sub, UIntSub) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint32_t, uint32, mul, UIntMult) #elif defined(PSNIP_SAFE_HAVE_LARGER_UINT32) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint32_t, uint32, add, 0xffffffffUL) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint32_t, uint32, sub, 0xffffffffUL) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint32_t, uint32, mul, 0xffffffffUL) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(psnip_uint32_t, uint32, 0xffffffffUL) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(psnip_uint32_t, uint32, 0xffffffffUL) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(psnip_uint32_t, uint32, 0xffffffffUL) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(psnip_uint32_t, uint32, 0xffffffffUL) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(psnip_uint32_t, uint32, 0xffffffffUL) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int64_t, int64, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int64_t, int64, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_int64_t, int64, mul) #elif defined(PSNIP_SAFE_HAVE_LARGER_INT64) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int64_t, int64, add, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int64_t, int64, sub, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) PSNIP_SAFE_DEFINE_PROMOTED_SIGNED_BINARY_OP(psnip_int64_t, int64, mul, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) #else PSNIP_SAFE_DEFINE_SIGNED_ADD(psnip_int64_t, int64, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) PSNIP_SAFE_DEFINE_SIGNED_SUB(psnip_int64_t, int64, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) PSNIP_SAFE_DEFINE_SIGNED_MUL(psnip_int64_t, int64, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) #endif PSNIP_SAFE_DEFINE_SIGNED_DIV(psnip_int64_t, int64, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) PSNIP_SAFE_DEFINE_SIGNED_MOD(psnip_int64_t, int64, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) PSNIP_SAFE_DEFINE_SIGNED_NEG(psnip_int64_t, int64, (-0x7fffffffffffffffLL-1), 0x7fffffffffffffffLL) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint64_t, uint64, add) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint64_t, uint64, sub) PSNIP_SAFE_DEFINE_BUILTIN_BINARY_OP(psnip_uint64_t, uint64, mul) #elif defined(PSNIP_SAFE_HAVE_INTSAFE_H) && defined(_WIN32) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint64_t, uint64, add, ULongLongAdd) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint64_t, uint64, sub, ULongLongSub) PSNIP_SAFE_DEFINE_INTSAFE(psnip_uint64_t, uint64, mul, ULongLongMult) #elif defined(PSNIP_SAFE_HAVE_LARGER_UINT64) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint64_t, uint64, add, 0xffffffffffffffffULL) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint64_t, uint64, sub, 0xffffffffffffffffULL) PSNIP_SAFE_DEFINE_PROMOTED_UNSIGNED_BINARY_OP(psnip_uint64_t, uint64, mul, 0xffffffffffffffffULL) #else PSNIP_SAFE_DEFINE_UNSIGNED_ADD(psnip_uint64_t, uint64, 0xffffffffffffffffULL) PSNIP_SAFE_DEFINE_UNSIGNED_SUB(psnip_uint64_t, uint64, 0xffffffffffffffffULL) PSNIP_SAFE_DEFINE_UNSIGNED_MUL(psnip_uint64_t, uint64, 0xffffffffffffffffULL) #endif PSNIP_SAFE_DEFINE_UNSIGNED_DIV(psnip_uint64_t, uint64, 0xffffffffffffffffULL) PSNIP_SAFE_DEFINE_UNSIGNED_MOD(psnip_uint64_t, uint64, 0xffffffffffffffffULL) #endif /* !defined(PSNIP_SAFE_NO_FIXED) */ #define PSNIP_SAFE_C11_GENERIC_SELECTION(res, op) \ _Generic((*res), \ char: psnip_safe_char_##op, \ unsigned char: psnip_safe_uchar_##op, \ short: psnip_safe_short_##op, \ unsigned short: psnip_safe_ushort_##op, \ int: psnip_safe_int_##op, \ unsigned int: psnip_safe_uint_##op, \ long: psnip_safe_long_##op, \ unsigned long: psnip_safe_ulong_##op, \ long long: psnip_safe_llong_##op, \ unsigned long long: psnip_safe_ullong_##op) #define PSNIP_SAFE_C11_GENERIC_BINARY_OP(op, res, a, b) \ PSNIP_SAFE_C11_GENERIC_SELECTION(res, op)(res, a, b) #define PSNIP_SAFE_C11_GENERIC_UNARY_OP(op, res, v) \ PSNIP_SAFE_C11_GENERIC_SELECTION(res, op)(res, v) #if defined(PSNIP_SAFE_HAVE_BUILTIN_OVERFLOW) #define psnip_safe_add(res, a, b) !__builtin_add_overflow(a, b, res) #define psnip_safe_sub(res, a, b) !__builtin_sub_overflow(a, b, res) #define psnip_safe_mul(res, a, b) !__builtin_mul_overflow(a, b, res) #define psnip_safe_div(res, a, b) PSNIP_SAFE_C11_GENERIC_BINARY_OP(div, res, a, b) #define psnip_safe_mod(res, a, b) PSNIP_SAFE_C11_GENERIC_BINARY_OP(mod, res, a, b) #define psnip_safe_neg(res, v) PSNIP_SAFE_C11_GENERIC_UNARY_OP (neg, res, v) #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* The are no fixed-length or size selections because they cause an * error about _Generic specifying two compatible types. Hopefully * this doesn't cause problems on exotic platforms, but if it does * please let me know and I'll try to figure something out. */ #define psnip_safe_add(res, a, b) PSNIP_SAFE_C11_GENERIC_BINARY_OP(add, res, a, b) #define psnip_safe_sub(res, a, b) PSNIP_SAFE_C11_GENERIC_BINARY_OP(sub, res, a, b) #define psnip_safe_mul(res, a, b) PSNIP_SAFE_C11_GENERIC_BINARY_OP(mul, res, a, b) #define psnip_safe_div(res, a, b) PSNIP_SAFE_C11_GENERIC_BINARY_OP(div, res, a, b) #define psnip_safe_mod(res, a, b) PSNIP_SAFE_C11_GENERIC_BINARY_OP(mod, res, a, b) #define psnip_safe_neg(res, v) PSNIP_SAFE_C11_GENERIC_UNARY_OP (neg, res, v) #endif #include <setjmp.h> #define ws_safe_op_jmp(op, res, a, b, env) \ do { \ if(!psnip_safe_##op(res, a, b)) { \ longjmp(env, 1); \ } \ } while (0) #define ws_safe_add_jmp(res, a, b, env) ws_safe_op_jmp(add, res, a, b, env) #define ws_safe_sub_jmp(res, a, b, env) ws_safe_op_jmp(sub, res, a, b, env) #define ws_safe_mul_jmp(res, a, b, env) ws_safe_op_jmp(mul, res, a, b, env) #define ws_safe_div_jmp(res, a, b, env) ws_safe_op_jmp(div, res, a, b, env) #define ws_safe_mod_jmp(res, a, b, env) ws_safe_op_jmp(mod, res, a, b, env) #define ws_safe_neg_jmp(res, a, b, env) ws_safe_op_jmp(neg, res, a, b, env) #endif /* !defined(PSNIP_SAFE_H) */
C/C++
wireshark/wsutil/sign_ext.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WSUTIL_SIGN_EXT_H__ #define __WSUTIL_SIGN_EXT_H__ #include <glib.h> #include <wsutil/ws_assert.h> /* sign extension routines */ static inline guint32 ws_sign_ext32(guint32 val, int no_of_bits) { ws_assert (no_of_bits >= 0 && no_of_bits <= 32); if ((no_of_bits == 0) || (no_of_bits == 32)) return val; /* * Don't shift signed values left; that's not valid in C99, at * least, if the value is negative or if the shift count is * the number of bits in the value - 1, and we might get * compile-time or run-time complaints about that. */ if (val & (1U << (no_of_bits-1))) val |= (0xFFFFFFFFU << no_of_bits); return val; } static inline guint64 ws_sign_ext64(guint64 val, int no_of_bits) { ws_assert (no_of_bits >= 0 && no_of_bits <= 64); if ((no_of_bits == 0) || (no_of_bits == 64)) return val; /* * Don't shift signed values left; that's not valid in C99, at * least, if the value is negative or if the shift count is * the number of bits in the value - 1, and we might get * compile-time or run-time complaints about that. */ if (val & (G_GUINT64_CONSTANT(1) << (no_of_bits-1))) val |= (G_GUINT64_CONSTANT(0xFFFFFFFFFFFFFFFF) << no_of_bits); return val; } /* static inline guint64 ws_sign_ext64(guint64 val, int no_of_bits) { gint64 sval = (val << (64 - no_of_bits)); return (guint64) (sval >> (64 - no_of_bits)); } */ #endif /* __WSUTIL_SIGN_EXT_H__ */
C
wireshark/wsutil/sober128.c
/* This file is derived from sober128 implementation in corosync cluster engine. corosync cluster engine borrows the implementation from LibTomCrypt. The latest version of the original code can be found at http://www.libtom.net/LibTomCrypt/ according to which this code is in the Public Domain */ /* About LibTomCrypt: * --------------------------------------------------------------------- * LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, [email protected], http://www.libtom.net/LibTomCrypt/ */ #include "sober128.h" typedef unsigned long ulong32; typedef unsigned long long ulong64; /* ---- HELPER MACROS ---- */ #define STORE32L(x, y) \ { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \ (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); } #define LOAD32L(x, y) \ { x = ((unsigned long)((y)[3] & 255)<<24) | \ ((unsigned long)((y)[2] & 255)<<16) | \ ((unsigned long)((y)[1] & 255)<<8) | \ ((unsigned long)((y)[0] & 255)); } /* rotates the hard way */ #define ROR(x, y) ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL) /* Id: s128multab.h 213 2003-12-16 04:27:12Z ggr $ */ /* @(#)TuringMultab.h 1.3 (QUALCOMM) 02/09/03 */ /* Multiplication table for Turing using 0xD02B4367 */ static const ulong32 Multab[256] = { 0x00000000, 0xD02B4367, 0xED5686CE, 0x3D7DC5A9, 0x97AC41D1, 0x478702B6, 0x7AFAC71F, 0xAAD18478, 0x631582EF, 0xB33EC188, 0x8E430421, 0x5E684746, 0xF4B9C33E, 0x24928059, 0x19EF45F0, 0xC9C40697, 0xC62A4993, 0x16010AF4, 0x2B7CCF5D, 0xFB578C3A, 0x51860842, 0x81AD4B25, 0xBCD08E8C, 0x6CFBCDEB, 0xA53FCB7C, 0x7514881B, 0x48694DB2, 0x98420ED5, 0x32938AAD, 0xE2B8C9CA, 0xDFC50C63, 0x0FEE4F04, 0xC154926B, 0x117FD10C, 0x2C0214A5, 0xFC2957C2, 0x56F8D3BA, 0x86D390DD, 0xBBAE5574, 0x6B851613, 0xA2411084, 0x726A53E3, 0x4F17964A, 0x9F3CD52D, 0x35ED5155, 0xE5C61232, 0xD8BBD79B, 0x089094FC, 0x077EDBF8, 0xD755989F, 0xEA285D36, 0x3A031E51, 0x90D29A29, 0x40F9D94E, 0x7D841CE7, 0xADAF5F80, 0x646B5917, 0xB4401A70, 0x893DDFD9, 0x59169CBE, 0xF3C718C6, 0x23EC5BA1, 0x1E919E08, 0xCEBADD6F, 0xCFA869D6, 0x1F832AB1, 0x22FEEF18, 0xF2D5AC7F, 0x58042807, 0x882F6B60, 0xB552AEC9, 0x6579EDAE, 0xACBDEB39, 0x7C96A85E, 0x41EB6DF7, 0x91C02E90, 0x3B11AAE8, 0xEB3AE98F, 0xD6472C26, 0x066C6F41, 0x09822045, 0xD9A96322, 0xE4D4A68B, 0x34FFE5EC, 0x9E2E6194, 0x4E0522F3, 0x7378E75A, 0xA353A43D, 0x6A97A2AA, 0xBABCE1CD, 0x87C12464, 0x57EA6703, 0xFD3BE37B, 0x2D10A01C, 0x106D65B5, 0xC04626D2, 0x0EFCFBBD, 0xDED7B8DA, 0xE3AA7D73, 0x33813E14, 0x9950BA6C, 0x497BF90B, 0x74063CA2, 0xA42D7FC5, 0x6DE97952, 0xBDC23A35, 0x80BFFF9C, 0x5094BCFB, 0xFA453883, 0x2A6E7BE4, 0x1713BE4D, 0xC738FD2A, 0xC8D6B22E, 0x18FDF149, 0x258034E0, 0xF5AB7787, 0x5F7AF3FF, 0x8F51B098, 0xB22C7531, 0x62073656, 0xABC330C1, 0x7BE873A6, 0x4695B60F, 0x96BEF568, 0x3C6F7110, 0xEC443277, 0xD139F7DE, 0x0112B4B9, 0xD31DD2E1, 0x03369186, 0x3E4B542F, 0xEE601748, 0x44B19330, 0x949AD057, 0xA9E715FE, 0x79CC5699, 0xB008500E, 0x60231369, 0x5D5ED6C0, 0x8D7595A7, 0x27A411DF, 0xF78F52B8, 0xCAF29711, 0x1AD9D476, 0x15379B72, 0xC51CD815, 0xF8611DBC, 0x284A5EDB, 0x829BDAA3, 0x52B099C4, 0x6FCD5C6D, 0xBFE61F0A, 0x7622199D, 0xA6095AFA, 0x9B749F53, 0x4B5FDC34, 0xE18E584C, 0x31A51B2B, 0x0CD8DE82, 0xDCF39DE5, 0x1249408A, 0xC26203ED, 0xFF1FC644, 0x2F348523, 0x85E5015B, 0x55CE423C, 0x68B38795, 0xB898C4F2, 0x715CC265, 0xA1778102, 0x9C0A44AB, 0x4C2107CC, 0xE6F083B4, 0x36DBC0D3, 0x0BA6057A, 0xDB8D461D, 0xD4630919, 0x04484A7E, 0x39358FD7, 0xE91ECCB0, 0x43CF48C8, 0x93E40BAF, 0xAE99CE06, 0x7EB28D61, 0xB7768BF6, 0x675DC891, 0x5A200D38, 0x8A0B4E5F, 0x20DACA27, 0xF0F18940, 0xCD8C4CE9, 0x1DA70F8E, 0x1CB5BB37, 0xCC9EF850, 0xF1E33DF9, 0x21C87E9E, 0x8B19FAE6, 0x5B32B981, 0x664F7C28, 0xB6643F4F, 0x7FA039D8, 0xAF8B7ABF, 0x92F6BF16, 0x42DDFC71, 0xE80C7809, 0x38273B6E, 0x055AFEC7, 0xD571BDA0, 0xDA9FF2A4, 0x0AB4B1C3, 0x37C9746A, 0xE7E2370D, 0x4D33B375, 0x9D18F012, 0xA06535BB, 0x704E76DC, 0xB98A704B, 0x69A1332C, 0x54DCF685, 0x84F7B5E2, 0x2E26319A, 0xFE0D72FD, 0xC370B754, 0x135BF433, 0xDDE1295C, 0x0DCA6A3B, 0x30B7AF92, 0xE09CECF5, 0x4A4D688D, 0x9A662BEA, 0xA71BEE43, 0x7730AD24, 0xBEF4ABB3, 0x6EDFE8D4, 0x53A22D7D, 0x83896E1A, 0x2958EA62, 0xF973A905, 0xC40E6CAC, 0x14252FCB, 0x1BCB60CF, 0xCBE023A8, 0xF69DE601, 0x26B6A566, 0x8C67211E, 0x5C4C6279, 0x6131A7D0, 0xB11AE4B7, 0x78DEE220, 0xA8F5A147, 0x958864EE, 0x45A32789, 0xEF72A3F1, 0x3F59E096, 0x0224253F, 0xD20F6658, }; /* Id: s128sbox.h 213 2003-12-16 04:27:12Z ggr $ */ /* Sbox for SOBER-128 */ /* * This is really the combination of two SBoxes; the least significant * 24 bits comes from: * 8->32 Sbox generated by Millan et. al. at Queensland University of * Technology. See: E. Dawson, W. Millan, L. Burnett, G. Carter, * "On the Design of 8*32 S-boxes". Unpublished report, by the * Information Systems Research Centre, * Queensland University of Technology, 1999. * * The most significant 8 bits are the Skipjack "F table", which can be * found at http://csrc.nist.gov/CryptoToolkit/skipjack/skipjack.pdf . * In this optimised table, though, the intent is to XOR the word from * the table selected by the high byte with the input word. Thus, the * high byte is actually the Skipjack F-table entry XORED with its * table index. */ static const ulong32 Sbox[256] = { 0xa3aa1887, 0xd65e435c, 0x0b65c042, 0x800e6ef4, 0xfc57ee20, 0x4d84fed3, 0xf066c502, 0xf354e8ae, 0xbb2ee9d9, 0x281f38d4, 0x1f829b5d, 0x735cdf3c, 0x95864249, 0xbc2e3963, 0xa1f4429f, 0xf6432c35, 0xf7f40325, 0x3cc0dd70, 0x5f973ded, 0x9902dc5e, 0xda175b42, 0x590012bf, 0xdc94d78c, 0x39aab26b, 0x4ac11b9a, 0x8c168146, 0xc3ea8ec5, 0x058ac28f, 0x52ed5c0f, 0x25b4101c, 0x5a2db082, 0x370929e1, 0x2a1843de, 0xfe8299fc, 0x202fbc4b, 0x833915dd, 0x33a803fa, 0xd446b2de, 0x46233342, 0x4fcee7c3, 0x3ad607ef, 0x9e97ebab, 0x507f859b, 0xe81f2e2f, 0xc55b71da, 0xd7e2269a, 0x1339c3d1, 0x7ca56b36, 0xa6c9def2, 0xb5c9fc5f, 0x5927b3a3, 0x89a56ddf, 0xc625b510, 0x560f85a7, 0xace82e71, 0x2ecb8816, 0x44951e2a, 0x97f5f6af, 0xdfcbc2b3, 0xce4ff55d, 0xcb6b6214, 0x2b0b83e3, 0x549ea6f5, 0x9de041af, 0x792f1f17, 0xf73b99ee, 0x39a65ec0, 0x4c7016c6, 0x857709a4, 0xd6326e01, 0xc7b280d9, 0x5cfb1418, 0xa6aff227, 0xfd548203, 0x506b9d96, 0xa117a8c0, 0x9cd5bf6e, 0xdcee7888, 0x61fcfe64, 0xf7a193cd, 0x050d0184, 0xe8ae4930, 0x88014f36, 0xd6a87088, 0x6bad6c2a, 0x1422c678, 0xe9204de7, 0xb7c2e759, 0x0200248e, 0x013b446b, 0xda0d9fc2, 0x0414a895, 0x3a6cc3a1, 0x56fef170, 0x86c19155, 0xcf7b8a66, 0x551b5e69, 0xb4a8623e, 0xa2bdfa35, 0xc4f068cc, 0x573a6acd, 0x6355e936, 0x03602db9, 0x0edf13c1, 0x2d0bb16d, 0x6980b83c, 0xfeb23763, 0x3dd8a911, 0x01b6bc13, 0xf55579d7, 0xf55c2fa8, 0x19f4196e, 0xe7db5476, 0x8d64a866, 0xc06e16ad, 0xb17fc515, 0xc46feb3c, 0x8bc8a306, 0xad6799d9, 0x571a9133, 0x992466dd, 0x92eb5dcd, 0xac118f50, 0x9fafb226, 0xa1b9cef3, 0x3ab36189, 0x347a19b1, 0x62c73084, 0xc27ded5c, 0x6c8bc58f, 0x1cdde421, 0xed1e47fb, 0xcdcc715e, 0xb9c0ff99, 0x4b122f0f, 0xc4d25184, 0xaf7a5e6c, 0x5bbf18bc, 0x8dd7c6e0, 0x5fb7e420, 0x521f523f, 0x4ad9b8a2, 0xe9da1a6b, 0x97888c02, 0x19d1e354, 0x5aba7d79, 0xa2cc7753, 0x8c2d9655, 0x19829da1, 0x531590a7, 0x19c1c149, 0x3d537f1c, 0x50779b69, 0xed71f2b7, 0x463c58fa, 0x52dc4418, 0xc18c8c76, 0xc120d9f0, 0xafa80d4d, 0x3b74c473, 0xd09410e9, 0x290e4211, 0xc3c8082b, 0x8f6b334a, 0x3bf68ed2, 0xa843cc1b, 0x8d3c0ff3, 0x20e564a0, 0xf8f55a4f, 0x2b40f8e7, 0xfea7f15f, 0xcf00fe21, 0x8a6d37d6, 0xd0d506f1, 0xade00973, 0xefbbde36, 0x84670fa8, 0xfa31ab9e, 0xaedab618, 0xc01f52f5, 0x6558eb4f, 0x71b9e343, 0x4b8d77dd, 0x8cb93da6, 0x740fd52d, 0x425412f8, 0xc5a63360, 0x10e53ad0, 0x5a700f1c, 0x8324ed0b, 0xe53dc1ec, 0x1a366795, 0x6d549d15, 0xc5ce46d7, 0xe17abe76, 0x5f48e0a0, 0xd0f07c02, 0x941249b7, 0xe49ed6ba, 0x37a47f78, 0xe1cfffbd, 0xb007ca84, 0xbb65f4da, 0xb59f35da, 0x33d2aa44, 0x417452ac, 0xc0d674a7, 0x2d61a46a, 0xdc63152a, 0x3e12b7aa, 0x6e615927, 0xa14fb118, 0xa151758d, 0xba81687b, 0xe152f0b3, 0x764254ed, 0x34c77271, 0x0a31acab, 0x54f94aec, 0xb9e994cd, 0x574d9e81, 0x5b623730, 0xce8a21e8, 0x37917f0b, 0xe8a9b5d6, 0x9697adf8, 0xf3d30431, 0x5dcac921, 0x76b35d46, 0xaa430a36, 0xc2194022, 0x22bca65e, 0xdaec70ba, 0xdfaea8cc, 0x777bae8b, 0x242924d5, 0x1f098a5a, 0x4b396b81, 0x55de2522, 0x435c1cb8, 0xaeb8fe1d, 0x9db3c697, 0x5b164f83, 0xe0c16376, 0xa319224c, 0xd0203b35, 0x433ac0fe, 0x1466a19a, 0x45f0b24f, 0x51fda998, 0xc0d52d71, 0xfa0896a8, 0xf9e6053f, 0xa4b0d300, 0xd499cbcc, 0xb95e3d40, }; /* Implementation of SOBER-128 by Tom St Denis. * Based on s128fast.c reference code supplied by Greg Rose of QUALCOMM. */ /* don't change these... */ #define N 17 #define FOLD N /* how many iterations of folding to do */ #define INITKONST 0x6996c53a /* value of KONST to use during key loading */ #define KEYP 15 /* where to insert key words */ #define FOLDP 4 /* where to insert non-linear feedback */ static ulong32 BYTE2WORD(const unsigned char *b) { ulong32 t; LOAD32L(t, b); return t; } static void XORWORD(ulong32 w, unsigned char *b) { ulong32 t; LOAD32L(t, b); t ^= w; STORE32L(t, b); } /* give correct offset for the current position of the register, * where logically R[0] is at position "zero". */ #define OFF(zero, i) (((zero)+(i)) % N) /* step the LFSR */ /* After stepping, "zero" moves right one place */ #define STEP(R,z) \ R[OFF(z,0)] = R[OFF(z,15)] ^ R[OFF(z,4)] ^ (R[OFF(z,0)] << 8) ^ Multab[(R[OFF(z,0)] >> 24) & 0xFF]; static void cycle(ulong32 *R) { ulong32 t; int i; STEP(R,0); t = R[0]; for (i = 1; i < N; ++i) { R[i-1] = R[i]; } R[N-1] = t; } /* Return a non-linear function of some parts of the register. */ #define NLFUNC(c,z) \ { \ t = c->R[OFF(z,0)] + c->R[OFF(z,16)]; \ t ^= Sbox[(t >> 24) & 0xFF]; \ t = ROR(t, 8); \ t = ((t + c->R[OFF(z,1)]) ^ c->konst) + c->R[OFF(z,6)]; \ t ^= Sbox[(t >> 24) & 0xFF]; \ t = t + c->R[OFF(z,13)]; \ } static ulong32 nltap(sober128_prng *c) { ulong32 t; NLFUNC(c, 0); return t; } /* initialise to known state */ int sober128_start(sober128_prng *c) { int i; /* Register initialised to Fibonacci numbers */ c->R[0] = 1; c->R[1] = 1; for (i = 2; i < N; ++i) { c->R[i] = c->R[i-1] + c->R[i-2]; } c->konst = INITKONST; /* next add_entropy will be the key */ c->flag = 1; c->set = 0; return 0; } /* Save the current register state */ static void s128_savestate(sober128_prng *c) { int i; for (i = 0; i < N; ++i) { c->initR[i] = c->R[i]; } } /* initialise to previously saved register state */ static void s128_reloadstate(sober128_prng *c) { int i; for (i = 0; i < N; ++i) { c->R[i] = c->initR[i]; } } /* Initialise "konst" */ static void s128_genkonst(sober128_prng *c) { ulong32 newkonst; do { cycle(c->R); newkonst = nltap(c); } while ((newkonst & 0xFF000000) == 0); c->konst = newkonst; } /* Load key material into the register */ #define ADDKEY(k) \ c->R[KEYP] += (k); #define XORNL(nl) \ c->R[FOLDP] ^= (nl); /* nonlinear diffusion of register for key */ #define DROUND(z) STEP(c->R,z); NLFUNC(c,(z+1)); c->R[OFF((z+1),FOLDP)] ^= t; static void s128_diffuse(sober128_prng *c) { ulong32 t; /* relies on FOLD == N == 17! */ DROUND(0); DROUND(1); DROUND(2); DROUND(3); DROUND(4); DROUND(5); DROUND(6); DROUND(7); DROUND(8); DROUND(9); DROUND(10); DROUND(11); DROUND(12); DROUND(13); DROUND(14); DROUND(15); DROUND(16); } int sober128_add_entropy(const unsigned char *buf, unsigned long len, sober128_prng *c) { ulong32 i, k; if (c->flag == 1) { /* this is the first call to the add_entropy so this input is the key */ /* len must be multiple of 4 bytes */ /* assert ((len & 3) == 0); */ for (i = 0; i < len/4; i++) { k = BYTE2WORD(&buf[i*4]); ADDKEY(k); cycle(c->R); XORNL(nltap(c)); } /* also fold in the length of the key */ ADDKEY(len); /* now diffuse */ s128_diffuse(c); s128_genkonst(c); s128_savestate(c); c->nbuf = 0; c->flag = 0; c->set = 1; } else { /* ok we are adding an IV then... */ s128_reloadstate(c); /* len must be multiple of 4 bytes */ /* assert ((len & 3) == 0); */ for (i = 0; i < len/4; i++) { k = BYTE2WORD(&buf[i*4]); ADDKEY(k); cycle(c->R); XORNL(nltap(c)); } /* also fold in the length of the key */ ADDKEY(len); /* now diffuse */ s128_diffuse(c); c->nbuf = 0; } return 0; } /* XOR pseudo-random bytes into buffer */ #define SROUND(z) STEP(c->R,z); NLFUNC(c,(z+1)); XORWORD(t, buf+(z*4)); unsigned long sober128_read(unsigned char *buf, unsigned long nbytes, sober128_prng *c) { ulong32 t, tlen; tlen = nbytes; /* handle any previously buffered bytes */ while (c->nbuf != 0 && nbytes != 0) { *buf++ ^= c->sbuf & 0xFF; c->sbuf >>= 8; c->nbuf -= 8; --nbytes; } #ifndef SMALL_CODE /* do lots at a time, if there's enough to do */ while (nbytes >= N*4) { SROUND(0); SROUND(1); SROUND(2); SROUND(3); SROUND(4); SROUND(5); SROUND(6); SROUND(7); SROUND(8); SROUND(9); SROUND(10); SROUND(11); SROUND(12); SROUND(13); SROUND(14); SROUND(15); SROUND(16); buf += 4*N; nbytes -= 4*N; } #endif /* do small or odd size buffers the slow way */ while (4 <= nbytes) { cycle(c->R); t = nltap(c); XORWORD(t, buf); buf += 4; nbytes -= 4; } /* handle any trailing bytes */ if (nbytes != 0) { cycle(c->R); c->sbuf = nltap(c); c->nbuf = 32; while (c->nbuf != 0 && nbytes != 0) { *buf++ ^= c->sbuf & 0xFF; c->sbuf >>= 8; c->nbuf -= 8; --nbytes; } } return tlen; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/sober128.h
/** @file This file is derived from sober128 implementation in corosync cluster engine. corosync cluster engine borrows the implementation from LibTomCrypt. The latest version of the original code can be found at http://www.libtom.net/LibTomCrypt/ according to which this code is in the Public Domain */ /* About LibTomCrypt: * --------------------------------------------------------------------- * LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, [email protected], http://www.libtom.net/LibTomCrypt/ */ #ifndef _SOBER127_H #define _SOBER127_H #include "ws_symbol_export.h" typedef struct _sober128_prng { unsigned long R[17], /* Working storage for the shift register */ initR[17], /* saved register contents */ konst, /* key dependent constant */ sbuf; /* partial word encryption buffer */ int nbuf, /* number of part-word stream bits buffered */ flag, /* first add_entropy call or not? */ set; /* did we call add_entropy to set key? */ } sober128_prng; WS_DLL_PUBLIC int sober128_start(sober128_prng *prng); WS_DLL_PUBLIC int sober128_add_entropy(const unsigned char *buf, unsigned long len, sober128_prng *prng); WS_DLL_PUBLIC unsigned long sober128_read(unsigned char *buf, unsigned long len, sober128_prng *prng); #endif /* sober128.h */
C
wireshark/wsutil/socket.c
/* socket.c * Socket wrappers * * Copyright 2019, Gerald Combs * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "socket.h" #include <stdlib.h> #include <errno.h> #include <wsutil/inet_addr.h> #ifdef _WIN32 #include <wsutil/win32-utils.h> #define in_port_t guint16 #endif gchar * ws_init_sockets(void) { char *errmsg = NULL; #ifdef _WIN32 int err; WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { errmsg = ws_strdup_printf("Couldn't initialize Windows Sockets: %s", win32strerror(err)); } #endif return errmsg; } void ws_cleanup_sockets(void) { #ifdef _WIN32 /* XXX - any reason to check the error return? */ WSACleanup(); #endif } int ws_socket_ptoa(struct sockaddr_storage *dst, const gchar *src, guint16 def_port) { int ret = -1, af = -1; char *addr_src, *p; char *addr_str = NULL, *port_str = NULL; union { ws_in4_addr ip4; ws_in6_addr ip6; } addr; char *endptr; long num; in_port_t port; addr_src = g_strdup(src); /* Is it an IPv6/IPv4 literal address enclosed in braces? */ if (*addr_src == '[') { addr_str = addr_src + 1; if ((p = strchr(addr_str, ']')) == NULL) { errno = EINVAL; goto out; } *p++ = '\0'; if (*p == ':') { port_str = p + 1; } else if (*p != '\0') { errno = EINVAL; goto out; } if (ws_inet_pton6(addr_str, &addr.ip6)) { af = AF_INET6; } else if (ws_inet_pton4(addr_str, &addr.ip4)) { af = AF_INET; } else { errno = EINVAL; goto out; } } else { /* It is an IPv4 dotted decimal. */ addr_str = addr_src; if ((p = strchr(addr_str, ':')) != NULL) { *p++ = '\0'; port_str = p; } if (ws_inet_pton4(addr_str, &addr.ip4)) { af = AF_INET; } else { errno = EINVAL; goto out; } } if (port_str != NULL && *port_str != '\0') { num = strtol(port_str, &endptr, 10); /* We want the entire string to be a valid decimal representation. */ if (endptr == port_str || *endptr != '\0' || num < 0 || num > G_MAXUINT16) { errno = EINVAL; goto out; } port = g_htons(num); } else { port = g_htons(def_port); } /* sockaddr_storage is guaranteed to fit any sockaddr type. */ if (af == AF_INET6) { struct sockaddr_in6 *sa = (struct sockaddr_in6 *)dst; memset(sa, 0, sizeof(struct sockaddr_in6)); sa->sin6_family = AF_INET6; sa->sin6_port = port; memcpy(&sa->sin6_addr, &addr.ip6, sizeof(struct in6_addr)); ret = 0; } else if (af == AF_INET) { struct sockaddr_in *sa = (struct sockaddr_in *)dst; memset(sa, 0, sizeof(struct sockaddr_in)); sa->sin_family = AF_INET; sa->sin_port = port; memcpy(&sa->sin_addr, &addr.ip4, sizeof(struct in_addr)); ret = 0; } else { ws_assert_not_reached(); } out: g_free(addr_src); return ret; }
C/C++
wireshark/wsutil/socket.h
/** @file * Socket wrappers * * Copyright 2016, Dario Lombardo * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __SOCKET_H__ #define __SOCKET_H__ #include <wireshark.h> #if defined(_WIN32) && !defined(__CYGWIN__) #include <windows.h> #include <ws2tcpip.h> #include <winsock2.h> #include <process.h> #define socket_handle_t SOCKET #define socklen_t int #else /* * UN*X, or Windows pretending to be UN*X with the aid of Cygwin. */ #ifdef HAVE_UNISTD_H /* * For close(). */ #include <unistd.h> #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #define closesocket(socket) close(socket) #define socket_handle_t int #ifndef INVALID_SOCKET #define INVALID_SOCKET (-1) #endif #define SOCKET_ERROR (-1) #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef __cplusplus extern "C" { #endif /* * Initialize sockets. * * Returns NULL on success, a g_malloc()ed error message on failure. */ WS_DLL_PUBLIC gchar *ws_init_sockets(void); /* * Clean up sockets. */ WS_DLL_PUBLIC void ws_cleanup_sockets(void); /* * Convert the strings ipv4_address:port or [ipv6_address]:port to a * sockaddr object. Ports are optional. Receives default port * in host byte order. */ WS_DLL_PUBLIC int ws_socket_ptoa(struct sockaddr_storage *dst, const gchar *src, guint16 def_port); #ifdef __cplusplus } #endif #endif /* __SOCKET_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C
wireshark/wsutil/strnatcmp.c
/* strnatcmp.c * * Original code downloaded from: http://sourcefrog.net/projects/natsort/ strnatcmp.c -- Perform 'natural order' comparisons of strings in C. Copyright (C) 2000, 2004 by Martin Pool <mbp sourcefrog net> SPDX-License-Identifier: Zlib */ /* partial change history: * * 2004-10-10 mbp: Lift out character type dependencies into macros. * * Eric Sosman pointed out that ctype functions take a parameter whose * value must be that of an unsigned int, even on platforms that have * negative chars in their default char type. */ /* * Modified 2014-10-29 to use the g_ascii_XXX() routines; this avoids * locale-dependent behavior. The routine names were changed to * ws_ascii_XXX() to reflect this. */ #include "strnatcmp.h" #include <glib.h> /* These are defined as macros to make it easier to adapt this code to * different characters types or comparison functions. */ static int nat_isdigit(nat_char a) { return g_ascii_isdigit(a); } static int nat_isspace(nat_char a) { return g_ascii_isspace(a); } static nat_char nat_toupper(nat_char a) { return g_ascii_toupper(a); } static int compare_right(nat_char const *a, nat_char const *b) { int bias = 0; /* The longest run of digits wins. That aside, the greatest value wins, but we can't know that it will until we've scanned both numbers to know that they have the same magnitude, so we remember it in BIAS. */ for (;; a++, b++) { if (!nat_isdigit(*a) && !nat_isdigit(*b)) return bias; else if (!nat_isdigit(*a)) return -1; else if (!nat_isdigit(*b)) return +1; else if (*a < *b) { if (!bias) bias = -1; } else if (*a > *b) { if (!bias) bias = +1; } else if (!*a && !*b) return bias; } return 0; } static int compare_left(nat_char const *a, nat_char const *b) { /* Compare two left-aligned numbers: the first to have a different value wins. */ for (;; a++, b++) { if (!nat_isdigit(*a) && !nat_isdigit(*b)) return 0; else if (!nat_isdigit(*a)) return -1; else if (!nat_isdigit(*b)) return +1; else if (*a < *b) return -1; else if (*a > *b) return +1; } return 0; } static int strnatcmp0(nat_char const *a, nat_char const *b, int fold_case) { int ai, bi; nat_char ca, cb; int fractional, result; if (!a || !b) { if (!a && !b) return 0; if (!a) return -1; return +1; } ai = bi = 0; while (1) { ca = a[ai]; cb = b[bi]; /* skip over leading spaces or zeros */ while (nat_isspace(ca)) ca = a[++ai]; while (nat_isspace(cb)) cb = b[++bi]; /* process run of digits */ if (nat_isdigit(ca) && nat_isdigit(cb)) { fractional = (ca == '0' || cb == '0'); if (fractional) { if ((result = compare_left(a+ai, b+bi)) != 0) return result; } else { if ((result = compare_right(a+ai, b+bi)) != 0) return result; } } if (!ca && !cb) { /* The strings compare the same. Perhaps the caller will want to call strcmp to break the tie. */ return 0; } if (fold_case) { ca = nat_toupper(ca); cb = nat_toupper(cb); } if (ca < cb) return -1; else if (ca > cb) return +1; ++ai; ++bi; } } int ws_ascii_strnatcmp(nat_char const *a, nat_char const *b) { return strnatcmp0(a, b, 0); } /* Compare, recognizing numeric string and ignoring case. */ int ws_ascii_strnatcasecmp(nat_char const *a, nat_char const *b) { return strnatcmp0(a, b, 1); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/strnatcmp.h
/** @file * * Original code downloaded from: http://sourcefrog.net/projects/natsort/ strnatcmp.c -- Perform 'natural order' comparisons of strings in C. Copyright (C) 2000, 2004 by Martin Pool <mbp sourcefrog net> SPDX-License-Identifier: Zlib */ #ifndef STRNATCMP_H #define STRNATCMP_H #include "ws_symbol_export.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* CUSTOMIZATION SECTION * * You can change this typedef, but must then also change the inline * functions in strnatcmp.c */ typedef char nat_char; WS_DLL_PUBLIC int ws_ascii_strnatcmp(nat_char const *a, nat_char const *b); WS_DLL_PUBLIC int ws_ascii_strnatcasecmp(nat_char const *a, nat_char const *b); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* STRNATCMP_H */
C
wireshark/wsutil/strptime.c
/* Convert a string representation of time to a time value. Copyright (C) 1996, 1997, 1998, 1999, 2000 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 1996. SPDX-License-Identifier: LGPL-2.0-or-later */ /* XXX This version of the implementation is not really complete. Some of the fields cannot add information alone. But if seeing some of them in the same format (such as year, week and weekday) this is enough information for determining the date. */ #include "config.h" #include "strptime.h" #include <ctype.h> #include <string.h> #include <glib.h> #ifdef _LIBC # include "../locale/localeinfo.h" #endif #ifndef __P # if defined (__GNUC__) || (defined (__STDC__) && __STDC__) # define __P(args) args # else # define __P(args) () # endif /* GCC. */ #endif /* Not __P. */ #if ! HAVE_LOCALTIME_R && ! defined localtime_r # ifdef _LIBC # define localtime_r __localtime_r # else /* Approximate localtime_r as best we can in its absence. */ # define localtime_r my_localtime_r static struct tm *localtime_r __P ((const time_t *, struct tm *)); static struct tm * localtime_r (const time_t *t, struct tm *tp) { struct tm *l = localtime (t); if (! l) return 0; *tp = *l; return tp; } # endif /* ! _LIBC */ #endif /* ! HAVE_LOCALTIME_R && ! defined (localtime_r) */ #define match_char(ch1, ch2) if (ch1 != ch2) return NULL #if defined __GNUC__ && __GNUC__ >= 2 # define match_string(cs1, s2) \ ({ size_t len = strlen (cs1); \ int result = g_ascii_strncasecmp ((cs1), (s2), len) == 0; \ if (result) (s2) += len; \ result; }) #else /* Oh come on. Get a reasonable compiler. */ # define match_string(cs1, s2) \ (g_ascii_strncasecmp ((cs1), (s2), strlen (cs1)) ? 0 : ((s2) += strlen (cs1), 1)) #endif /* We intentionally do not use isdigit() for testing because this will lead to problems with the wide character version. */ #define get_number(from, to, n) \ do { \ int __n = n; \ val = 0; \ while (*rp == ' ') \ ++rp; \ if (*rp < '0' || *rp > '9') \ return NULL; \ do { \ val *= 10; \ val += *rp++ - '0'; \ } while (--__n > 0 && val * 10 <= to && *rp >= '0' && *rp <= '9'); \ if (val < from || val > to) \ return NULL; \ } while (0) #ifdef _NL_CURRENT # define get_alt_number(from, to, n) \ ({ \ __label__ do_normal; \ if (*decided != raw) \ { \ const char *alts = _NL_CURRENT (LC_TIME, ALT_DIGITS); \ int __n = n; \ int any = 0; \ while (*rp == ' ') \ ++rp; \ val = 0; \ do { \ val *= 10; \ while (*alts != '\0') \ { \ size_t len = strlen (alts); \ if (g_ascii_strncasecmp (alts, rp, len) == 0) \ break; \ alts += len + 1; \ ++val; \ } \ if (*alts == '\0') \ { \ if (*decided == not && ! any) \ goto do_normal; \ /* If we haven't read anything it's an error. */ \ if (! any) \ return NULL; \ /* Correct the premature multiplication. */ \ val /= 10; \ break; \ } \ else \ *decided = loc; \ } while (--__n > 0 && val * 10 <= to); \ if (val < from || val > to) \ return NULL; \ } \ else \ { \ do_normal: \ get_number (from, to, n); \ } \ 0; \ }) #else # define get_alt_number(from, to, n) \ /* We don't have the alternate representation. */ \ get_number(from, to, n) #endif #define recursive(new_fmt) \ (*(new_fmt) != '\0' \ && (rp = strptime_internal (rp, (new_fmt), tm, decided, era_cnt)) != NULL) #ifdef _LIBC /* This is defined in locale/C-time.c in the GNU libc. */ extern const struct locale_data _nl_C_LC_TIME; extern const unsigned short int __mon_yday[2][13]; # define weekday_name (&_nl_C_LC_TIME.values[_NL_ITEM_INDEX (DAY_1)].string) # define ab_weekday_name \ (&_nl_C_LC_TIME.values[_NL_ITEM_INDEX (ABDAY_1)].string) # define month_name (&_nl_C_LC_TIME.values[_NL_ITEM_INDEX (MON_1)].string) # define ab_month_name (&_nl_C_LC_TIME.values[_NL_ITEM_INDEX (ABMON_1)].string) # define HERE_D_T_FMT (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (D_T_FMT)].string) # define HERE_D_FMT (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (D_FMT)].string) # define HERE_AM_STR (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (AM_STR)].string) # define HERE_PM_STR (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (PM_STR)].string) # define HERE_T_FMT_AMPM \ (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (T_FMT_AMPM)].string) # define HERE_T_FMT (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (T_FMT)].string) # define strncasecmp(s1, s2, n) __strncasecmp (s1, s2, n) #else static char const weekday_name[][10] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char const ab_weekday_name[][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char const month_name[][10] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char const ab_month_name[][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; # define HERE_D_T_FMT "%a %b %e %H:%M:%S %Y" # define HERE_D_FMT "%m/%d/%y" # define HERE_AM_STR "AM" # define HERE_PM_STR "PM" # define HERE_T_FMT_AMPM "%I:%M:%S %p" # define HERE_T_FMT "%H:%M:%S" const unsigned short int __mon_yday[2][13] = { /* Normal years. */ { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, /* Leap years. */ { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } }; #endif /* Status of lookup: do we use the locale data or the raw data? */ enum locale_status { not, loc, raw }; #ifndef __isleap /* Nonzero if YEAR is a leap year (every 4 years, except every 100th isn't, and every 400th is). */ # define __isleap(year) \ ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) #endif /* Compute the day of the week. */ static void day_of_the_week (struct tm *tm) { /* We know that January 1st 1970 was a Thursday (= 4). Compute the the difference between this data in the one on TM and so determine the weekday. */ int corr_year = 1900 + tm->tm_year - (tm->tm_mon < 2); int wday = (-473 + (365 * (tm->tm_year - 70)) + (corr_year / 4) - ((corr_year / 4) / 25) + ((corr_year / 4) % 25 < 0) + (((corr_year / 4) / 25) / 4) + __mon_yday[0][tm->tm_mon] + tm->tm_mday - 1); tm->tm_wday = ((wday % 7) + 7) % 7; } /* Compute the day of the year. */ static void day_of_the_year (struct tm *tm) { tm->tm_yday = (__mon_yday[__isleap (1900 + tm->tm_year)][tm->tm_mon] + (tm->tm_mday - 1)); } static char * #ifdef _LIBC internal_function #endif strptime_internal __P ((const char *rp, const char *fmt, struct tm *tm, enum locale_status *decided, int era_cnt)); static char * #ifdef _LIBC internal_function #endif strptime_internal ( const char *rp, const char *fmt, struct tm *tm, enum locale_status *decided, int era_cnt) { // const char *rp_backup; int cnt; int val; int have_I, is_pm; int century, want_century; int want_era; int have_wday, want_xday; int have_yday; int have_mon, have_mday; #ifdef _NL_CURRENT size_t num_eras; #endif // struct era_entry *era; have_I = is_pm = 0; century = -1; want_century = 0; want_era = 0; // era = NULL; have_wday = want_xday = have_yday = have_mon = have_mday = 0; while (*fmt != '\0') { /* A white space in the format string matches 0 more or white space in the input string. */ if (isspace (*fmt)) { while (isspace (*rp)) ++rp; ++fmt; continue; } /* Any character but `%' must be matched by the same character in the input string. */ if (*fmt != '%') { match_char (*fmt++, *rp++); continue; } ++fmt; #ifndef _NL_CURRENT /* We need this for handling the `E' modifier. */ start_over: #endif /* Make back up of current processing pointer. */ //rp_backup = rp; switch (*fmt++) { case '%': /* Match the `%' character itself. */ match_char ('%', *rp++); break; case 'a': case 'A': /* Match day of week. */ for (cnt = 0; cnt < 7; ++cnt) { #ifdef _NL_CURRENT if (*decided !=raw) { if (match_string (_NL_CURRENT (LC_TIME, DAY_1 + cnt), rp)) { if (*decided == not && strcmp (_NL_CURRENT (LC_TIME, DAY_1 + cnt), weekday_name[cnt])) *decided = loc; break; } if (match_string (_NL_CURRENT (LC_TIME, ABDAY_1 + cnt), rp)) { if (*decided == not && strcmp (_NL_CURRENT (LC_TIME, ABDAY_1 + cnt), ab_weekday_name[cnt])) *decided = loc; break; } } #endif if (*decided != loc && (match_string (weekday_name[cnt], rp) || match_string (ab_weekday_name[cnt], rp))) { *decided = raw; break; } } if (cnt == 7) /* Does not match a weekday name. */ return NULL; tm->tm_wday = cnt; have_wday = 1; break; case 'b': case 'B': case 'h': /* Match month name. */ for (cnt = 0; cnt < 12; ++cnt) { #ifdef _NL_CURRENT if (*decided !=raw) { if (match_string (_NL_CURRENT (LC_TIME, MON_1 + cnt), rp)) { if (*decided == not && strcmp (_NL_CURRENT (LC_TIME, MON_1 + cnt), month_name[cnt])) *decided = loc; break; } if (match_string (_NL_CURRENT (LC_TIME, ABMON_1 + cnt), rp)) { if (*decided == not && strcmp (_NL_CURRENT (LC_TIME, ABMON_1 + cnt), ab_month_name[cnt])) *decided = loc; break; } } #endif if (match_string (month_name[cnt], rp) || match_string (ab_month_name[cnt], rp)) { *decided = raw; break; } } if (cnt == 12) /* Does not match a month name. */ return NULL; tm->tm_mon = cnt; want_xday = 1; break; case 'c': /* Match locale's date and time format. */ #ifdef _NL_CURRENT if (*decided != raw) { if (!recursive (_NL_CURRENT (LC_TIME, D_T_FMT))) { if (*decided == loc) return NULL; else rp = rp_backup; } else { if (*decided == not && strcmp (_NL_CURRENT (LC_TIME, D_T_FMT), HERE_D_T_FMT)) *decided = loc; want_xday = 1; break; } *decided = raw; } #endif if (!recursive (HERE_D_T_FMT)) return NULL; want_xday = 1; break; case 'C': /* Match century number. */ #ifdef _NL_CURRENT match_century: #endif get_number (0, 99, 2); century = val; want_xday = 1; break; case 'd': case 'e': /* Match day of month. */ get_number (1, 31, 2); tm->tm_mday = val; have_mday = 1; want_xday = 1; break; case 'F': if (!recursive ("%Y-%m-%d")) return NULL; want_xday = 1; break; case 'x': #ifdef _NL_CURRENT if (*decided != raw) { if (!recursive (_NL_CURRENT (LC_TIME, D_FMT))) { if (*decided == loc) return NULL; else rp = rp_backup; } else { if (*decided == not && strcmp (_NL_CURRENT (LC_TIME, D_FMT), HERE_D_FMT)) *decided = loc; want_xday = 1; break; } *decided = raw; } #endif /* Fall through. */ case 'D': /* Match standard day format. */ if (!recursive (HERE_D_FMT)) return NULL; want_xday = 1; break; case 'k': case 'H': /* Match hour in 24-hour clock. */ get_number (0, 23, 2); tm->tm_hour = val; have_I = 0; break; case 'I': /* Match hour in 12-hour clock. */ get_number (1, 12, 2); tm->tm_hour = val % 12; have_I = 1; break; case 'j': /* Match day number of year. */ get_number (1, 366, 3); tm->tm_yday = val - 1; have_yday = 1; break; case 'm': /* Match number of month. */ get_number (1, 12, 2); tm->tm_mon = val - 1; have_mon = 1; want_xday = 1; break; case 'M': /* Match minute. */ get_number (0, 59, 2); tm->tm_min = val; break; case 'n': case 't': /* Match any white space. */ while (isspace (*rp)) ++rp; break; case 'p': /* Match locale's equivalent of AM/PM. */ #ifdef _NL_CURRENT if (*decided != raw) { if (match_string (_NL_CURRENT (LC_TIME, AM_STR), rp)) { if (strcmp (_NL_CURRENT (LC_TIME, AM_STR), HERE_AM_STR)) *decided = loc; break; } if (match_string (_NL_CURRENT (LC_TIME, PM_STR), rp)) { if (strcmp (_NL_CURRENT (LC_TIME, PM_STR), HERE_PM_STR)) *decided = loc; is_pm = 1; break; } *decided = raw; } #endif if (!match_string (HERE_AM_STR, rp)) { if (match_string (HERE_PM_STR, rp)) is_pm = 1; else return NULL; } break; case 'r': #ifdef _NL_CURRENT if (*decided != raw) { if (!recursive (_NL_CURRENT (LC_TIME, T_FMT_AMPM))) { if (*decided == loc) return NULL; else rp = rp_backup; } else { if (*decided == not && strcmp (_NL_CURRENT (LC_TIME, T_FMT_AMPM), HERE_T_FMT_AMPM)) *decided = loc; break; } *decided = raw; } #endif if (!recursive (HERE_T_FMT_AMPM)) return NULL; break; case 'R': if (!recursive ("%H:%M")) return NULL; break; case 's': { /* The number of seconds may be very high so we cannot use the `get_number' macro. Instead read the number character for character and construct the result while doing this. */ time_t secs = 0; if (*rp < '0' || *rp > '9') /* We need at least one digit. */ return NULL; do { secs *= 10; secs += *rp++ - '0'; } while (*rp >= '0' && *rp <= '9'); if (localtime_r (&secs, tm) == NULL) /* Error in function. */ return NULL; } break; case 'S': get_number (0, 61, 2); tm->tm_sec = val; break; case 'X': #ifdef _NL_CURRENT if (*decided != raw) { if (!recursive (_NL_CURRENT (LC_TIME, T_FMT))) { if (*decided == loc) return NULL; else rp = rp_backup; } else { if (strcmp (_NL_CURRENT (LC_TIME, T_FMT), HERE_T_FMT)) *decided = loc; break; } *decided = raw; } #endif /* Fall through. */ case 'T': if (!recursive (HERE_T_FMT)) return NULL; break; case 'u': get_number (1, 7, 1); tm->tm_wday = val % 7; have_wday = 1; break; case 'g': get_number (0, 99, 2); /* XXX This cannot determine any field in TM. */ break; case 'G': if (*rp < '0' || *rp > '9') return NULL; /* XXX Ignore the number since we would need some more information to compute a real date. */ do ++rp; while (*rp >= '0' && *rp <= '9'); break; case 'U': case 'V': case 'W': get_number (0, 53, 2); /* XXX This cannot determine any field in TM without some information. */ break; case 'w': /* Match number of weekday. */ get_number (0, 6, 1); tm->tm_wday = val; have_wday = 1; break; case 'y': #ifdef _NL_CURRENT match_year_in_century: #endif /* Match year within century. */ get_number (0, 99, 2); /* The "Year 2000: The Millennium Rollover" paper suggests that values in the range 69-99 refer to the twentieth century. */ tm->tm_year = val >= 69 ? val : val + 100; /* Indicate that we want to use the century, if specified. */ want_century = 1; want_xday = 1; break; case 'Y': /* Match year including century number. */ get_number (0, 9999, 4); tm->tm_year = val - 1900; want_century = 0; want_xday = 1; break; case 'Z': /* XXX How to handle this? */ break; case 'E': #ifdef _NL_CURRENT switch (*fmt++) { case 'c': /* Match locale's alternate date and time format. */ if (*decided != raw) { const char *fmt = _NL_CURRENT (LC_TIME, ERA_D_T_FMT); if (*fmt == '\0') fmt = _NL_CURRENT (LC_TIME, D_T_FMT); if (!recursive (fmt)) { if (*decided == loc) return NULL; else rp = rp_backup; } else { if (strcmp (fmt, HERE_D_T_FMT)) *decided = loc; want_xday = 1; break; } *decided = raw; } /* The C locale has no era information, so use the normal representation. */ if (!recursive (HERE_D_T_FMT)) return NULL; want_xday = 1; break; case 'C': if (*decided != raw) { if (era_cnt >= 0) { era = _nl_select_era_entry (era_cnt); if (match_string (era->era_name, rp)) { *decided = loc; break; } else return NULL; } else { num_eras = _NL_CURRENT_WORD (LC_TIME, _NL_TIME_ERA_NUM_ENTRIES); for (era_cnt = 0; era_cnt < (int) num_eras; ++era_cnt, rp = rp_backup) { era = _nl_select_era_entry (era_cnt); if (match_string (era->era_name, rp)) { *decided = loc; break; } } if (era_cnt == (int) num_eras) { era_cnt = -1; if (*decided == loc) return NULL; } else break; } *decided = raw; } /* The C locale has no era information, so use the normal representation. */ goto match_century; case 'y': if (*decided == raw) goto match_year_in_century; get_number(0, 9999, 4); tm->tm_year = val; want_era = 1; want_xday = 1; break; case 'Y': if (*decided != raw) { num_eras = _NL_CURRENT_WORD (LC_TIME, _NL_TIME_ERA_NUM_ENTRIES); for (era_cnt = 0; era_cnt < (int) num_eras; ++era_cnt, rp = rp_backup) { era = _nl_select_era_entry (era_cnt); if (recursive (era->era_format)) break; } if (era_cnt == (int) num_eras) { era_cnt = -1; if (*decided == loc) return NULL; else rp = rp_backup; } else { *decided = loc; era_cnt = -1; break; } *decided = raw; } get_number (0, 9999, 4); tm->tm_year = val - 1900; want_century = 0; want_xday = 1; break; case 'x': if (*decided != raw) { const char *fmt = _NL_CURRENT (LC_TIME, ERA_D_FMT); if (*fmt == '\0') fmt = _NL_CURRENT (LC_TIME, D_FMT); if (!recursive (fmt)) { if (*decided == loc) return NULL; else rp = rp_backup; } else { if (strcmp (fmt, HERE_D_FMT)) *decided = loc; break; } *decided = raw; } if (!recursive (HERE_D_FMT)) return NULL; break; case 'X': if (*decided != raw) { const char *fmt = _NL_CURRENT (LC_TIME, ERA_T_FMT); if (*fmt == '\0') fmt = _NL_CURRENT (LC_TIME, T_FMT); if (!recursive (fmt)) { if (*decided == loc) return NULL; else rp = rp_backup; } else { if (strcmp (fmt, HERE_T_FMT)) *decided = loc; break; } *decided = raw; } if (!recursive (HERE_T_FMT)) return NULL; break; default: return NULL; } break; #else /* We have no information about the era format. Just use the normal format. */ if (*fmt != 'c' && *fmt != 'C' && *fmt != 'y' && *fmt != 'Y' && *fmt != 'x' && *fmt != 'X') /* This is an illegal format. */ return NULL; goto start_over; #endif case 'O': switch (*fmt++) { case 'd': case 'e': /* Match day of month using alternate numeric symbols. */ get_alt_number (1, 31, 2); tm->tm_mday = val; have_mday = 1; want_xday = 1; break; case 'H': /* Match hour in 24-hour clock using alternate numeric symbols. */ get_alt_number (0, 23, 2); tm->tm_hour = val; have_I = 0; break; case 'I': /* Match hour in 12-hour clock using alternate numeric symbols. */ get_alt_number (1, 12, 2); tm->tm_hour = val - 1; have_I = 1; break; case 'm': /* Match month using alternate numeric symbols. */ get_alt_number (1, 12, 2); tm->tm_mon = val - 1; have_mon = 1; want_xday = 1; break; case 'M': /* Match minutes using alternate numeric symbols. */ get_alt_number (0, 59, 2); tm->tm_min = val; break; case 'S': /* Match seconds using alternate numeric symbols. */ get_alt_number (0, 61, 2); tm->tm_sec = val; break; case 'U': case 'V': case 'W': get_alt_number (0, 53, 2); /* XXX This cannot determine any field in TM without further information. */ break; case 'w': /* Match number of weekday using alternate numeric symbols. */ get_alt_number (0, 6, 1); tm->tm_wday = val; have_wday = 1; break; case 'y': /* Match year within century using alternate numeric symbols. */ get_alt_number (0, 99, 2); tm->tm_year = val >= 69 ? val : val + 100; want_xday = 1; break; default: return NULL; } break; default: return NULL; } } if (have_I && is_pm) tm->tm_hour += 12; if (century != -1) { if (want_century) tm->tm_year = tm->tm_year % 100 + (century - 19) * 100; else /* Only the century, but not the year. Strange, but so be it. */ tm->tm_year = (century - 19) * 100; } #ifdef _NL_CURRENT if (era_cnt != -1) { era = _nl_select_era_entry(era_cnt); if (want_era) tm->tm_year = (era->start_date[0] + ((tm->tm_year - era->offset) * era->absolute_direction)); else /* Era start year assumed. */ tm->tm_year = era->start_date[0]; } else #endif if (want_era) return NULL; if (want_xday && !have_wday) { if ( !(have_mon && have_mday) && have_yday) { /* We don't have tm_mon and/or tm_mday, compute them. */ int t_mon = 0; while (__mon_yday[__isleap(1900 + tm->tm_year)][t_mon] <= tm->tm_yday) t_mon++; if (!have_mon) tm->tm_mon = t_mon - 1; if (!have_mday) tm->tm_mday = (tm->tm_yday - __mon_yday[__isleap(1900 + tm->tm_year)][t_mon - 1] + 1); } day_of_the_week (tm); } if (want_xday && !have_yday) day_of_the_year (tm); return (char *) rp; } char * strptime_gnulib ( const char *buf, const char *format, struct tm *tm) { enum locale_status decided; #ifdef _NL_CURRENT decided = not; #else decided = raw; #endif return strptime_internal (buf, format, tm, &decided, -1); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local Variables: * c-basic-offset: 2 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=2 tabstop=8 expandtab: * :indentSize=2:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/strptime.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __STRPTIME_H__ #define __STRPTIME_H__ #include <ws_symbol_export.h> #include <time.h> /* * Version of "strptime()", for the benefit of OSes that don't have it. */ WS_DLL_LOCAL char *strptime_gnulib(const char *s, const char *format, struct tm *tm); #endif
C
wireshark/wsutil/strtoi.c
/* strtoi.c * Utilities to convert strings to integers * * Copyright 2016, Dario Lombardo * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "strtoi.h" #include <errno.h> #include <wsutil/ws_assert.h> gboolean ws_strtoi64(const gchar* str, const gchar** endptr, gint64* cint) { gchar* end; gint64 val; ws_assert(cint); if (!str) { errno = EINVAL; return FALSE; } errno = 0; val = g_ascii_strtoll(str, &end, 10); if ((val == 0 && end == str) || (endptr == NULL && *end != '\0')) { *cint = 0; if (endptr != NULL) *endptr = end; errno = EINVAL; return FALSE; } if ((val == G_MAXINT64 || val == G_MININT64) && errno == ERANGE) { /* * Return the value, so our caller knows whether to * report the value as "too small" or "too large". */ *cint = val; if (endptr != NULL) *endptr = end; /* errno is already set */ return FALSE; } if (endptr != NULL) *endptr = end; *cint = val; return TRUE; } #define DEFINE_WS_STRTOI_BITS(bits) \ gboolean ws_strtoi##bits(const gchar* str, const gchar** endptr, gint##bits* cint) \ { \ gint64 val = 0; \ if (!ws_strtoi64(str, endptr, &val)) { \ /* \ * For ERANGE, return either G_MININT##bits or \ * G_MAXINT##bits so our caller knows whether \ * to report the value as "too small" or "too \ * large". \ * \ * For other errors, return 0, for parallelism \ * with ws_strtoi64(). \ */ \ if (errno == ERANGE) { \ if (val < 0) \ *cint = G_MININT##bits; \ else \ *cint = G_MAXINT##bits; \ } else \ *cint = 0; \ return FALSE; \ } \ if (val < G_MININT##bits) { \ /* \ * Return G_MININT##bits so our caller knows whether to \ * report the value as "too small" or "too large". \ */ \ *cint = G_MININT##bits; \ errno = ERANGE; \ return FALSE; \ } \ if (val > G_MAXINT##bits) { \ /* \ * Return G_MAXINT##bits so our caller knows whether to \ * report the value as "too small" or "too large". \ */ \ *cint = G_MAXINT##bits; \ errno = ERANGE; \ return FALSE; \ } \ *cint = (gint##bits)val; \ return TRUE; \ } DEFINE_WS_STRTOI_BITS(32) DEFINE_WS_STRTOI_BITS(16) DEFINE_WS_STRTOI_BITS(8) gboolean ws_strtoi(const gchar* str, const gchar** endptr, gint* cint) { gint64 val = 0; if (!ws_strtoi64(str, endptr, &val)) { /* * For ERANGE, return either G_MININT or * G_MAXINT so our caller knows whether * to report the value as "too small" or "too * large". * * For other errors, return 0, for parallelism * with ws_strtoi64(). */ if (errno == ERANGE) { if (val < 0) *cint = G_MININT; else *cint = G_MAXINT; } else *cint = 0; return FALSE; } if (val < G_MININT) { /* * Return G_MININT so our caller knows whether to * report the value as "too small" or "too large". */ *cint = G_MININT; errno = ERANGE; return FALSE; } if (val > G_MAXINT) { /* * Return G_MAXINT so our caller knows whether to * report the value as "too small" or "too large". */ *cint = G_MAXINT; errno = ERANGE; return FALSE; } *cint = (gint)val; return TRUE; } gboolean ws_basestrtou64(const gchar* str, const gchar** endptr, guint64* cint, int base) { gchar* end; guint64 val; ws_assert(cint); if (!str) { errno = EINVAL; return FALSE; } if (str[0] == '-' || str[0] == '+') { /* * Unsigned numbers don't have a sign. */ *cint = 0; if (endptr != NULL) *endptr = str; errno = EINVAL; return FALSE; } errno = 0; val = g_ascii_strtoull(str, &end, base); if ((val == 0 && end == str) || (endptr == NULL && *end != '\0')) { *cint = 0; if (endptr != NULL) *endptr = end; errno = EINVAL; return FALSE; } if (val == G_MAXUINT64 && errno == ERANGE) { /* * Return the value, because ws_strtoi64() does. */ *cint = val; if (endptr != NULL) *endptr = end; /* errno is already set */ return FALSE; } if (endptr != NULL) *endptr = end; *cint = val; return TRUE; } gboolean ws_strtou64(const gchar* str, const gchar** endptr, guint64* cint) { return ws_basestrtou64(str, endptr, cint, 10); } gboolean ws_hexstrtou64(const gchar* str, const gchar** endptr, guint64* cint) { return ws_basestrtou64(str, endptr, cint, 16); } #define DEFINE_WS_STRTOU_BITS(bits) \ gboolean ws_basestrtou##bits(const gchar* str, const gchar** endptr, guint##bits* cint, int base) \ { \ guint64 val; \ if (!ws_basestrtou64(str, endptr, &val, base)) { \ /* \ * For ERANGE, return G_MAXUINT##bits for parallelism \ * with ws_strtoi##bits(). \ * \ * For other errors, return 0, for parallelism \ * with ws_basestrtou64(). \ */ \ if (errno == ERANGE) \ *cint = G_MAXUINT##bits; \ else \ *cint = 0; \ return FALSE; \ } \ if (val > G_MAXUINT##bits) { \ /* \ * Return G_MAXUINT##bits for parallelism with \ * ws_strtoi##bits(). \ */ \ *cint = G_MAXUINT##bits; \ errno = ERANGE; \ return FALSE; \ } \ *cint = (guint##bits)val; \ return TRUE; \ } \ \ gboolean ws_strtou##bits(const gchar* str, const gchar** endptr, guint##bits* cint) \ { \ return ws_basestrtou##bits(str, endptr, cint, 10); \ } \ \ gboolean ws_hexstrtou##bits(const gchar* str, const gchar** endptr, guint##bits* cint) \ { \ return ws_basestrtou##bits(str, endptr, cint, 16); \ } DEFINE_WS_STRTOU_BITS(32) DEFINE_WS_STRTOU_BITS(16) DEFINE_WS_STRTOU_BITS(8) gboolean ws_basestrtou(const gchar* str, const gchar** endptr, guint* cint, int base) { guint64 val; if (!ws_basestrtou64(str, endptr, &val, base)) { /* * For ERANGE, return G_MAXUINT for parallelism * with ws_strtoi(). * * For other errors, return 0, for parallelism * with ws_basestrtou64(). */ if (errno == ERANGE) *cint = G_MAXUINT; else *cint = 0; return FALSE; } if (val > G_MAXUINT) { /* * Return G_MAXUINT for parallelism with * ws_strtoi(). */ *cint = G_MAXUINT; errno = ERANGE; return FALSE; } *cint = (guint)val; return TRUE; } gboolean ws_strtou(const gchar* str, const gchar** endptr, guint* cint) { return ws_basestrtou(str, endptr, cint, 10); } \ gboolean ws_hexstrtou(const gchar* str, const gchar** endptr, guint* cint) { return ws_basestrtou(str, endptr, cint, 16); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=4 tabstop=8 noexpandtab: * :indentSize=4:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/strtoi.h
/** @file * Utilities to convert strings to integers * * Copyright 2016, Dario Lombardo * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef _WS_STRTOI_H #define _WS_STRTOI_H #include <glib.h> #include "ws_symbol_export.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * \brief Convert a decimal string to a signed/unsigned int, with error checks. * \param str The string to convert * \param endptr A pointer that will store a pointer to the first invalid * character in str, allowing a number to be parsed even if there is trailing * whitespace. If NULL, then the string is assumed to contain only valid * characters (or it will error out). * \param cint The converted integer * \return TRUE if the conversion succeeds, FALSE otherwise. * On error, errno is set to EINVAL for unrecognized input and ERANGE * if the resulting number does not fit in the type. */ WS_DLL_PUBLIC gboolean ws_strtoi64(const gchar* str, const gchar** endptr, gint64* cint); WS_DLL_PUBLIC gboolean ws_strtoi32(const gchar* str, const gchar** endptr, gint32* cint); WS_DLL_PUBLIC gboolean ws_strtoi16(const gchar* str, const gchar** endptr, gint16* cint); WS_DLL_PUBLIC gboolean ws_strtoi8 (const gchar* str, const gchar** endptr, gint8* cint); WS_DLL_PUBLIC gboolean ws_strtoi (const gchar* str, const gchar** endptr, gint* cint); WS_DLL_PUBLIC gboolean ws_strtou64(const gchar* str, const gchar** endptr, guint64* cint); WS_DLL_PUBLIC gboolean ws_strtou32(const gchar* str, const gchar** endptr, guint32* cint); WS_DLL_PUBLIC gboolean ws_strtou16(const gchar* str, const gchar** endptr, guint16* cint); WS_DLL_PUBLIC gboolean ws_strtou8 (const gchar* str, const gchar** endptr, guint8* cint); WS_DLL_PUBLIC gboolean ws_strtou (const gchar* str, const gchar** endptr, guint* cint); /* * \brief Convert a hexadecimal string to an unsigned int, with error checks. * \param str The string to convert * \param endptr A pointer that will store a pointer to the first invalid * character in str, allowing a number to be parsed even if there is trailing * whitespace. If NULL, then the string is assumed to contain only valid * characters (or it will error out). * \param cint The converted integer * \return TRUE if the conversion succeeds, FALSE otherwise. * On error, errno is set to EINVAL for unrecognized input and ERANGE * if the resulting number does not fit in the type. */ WS_DLL_PUBLIC gboolean ws_hexstrtou64(const gchar* str, const gchar** endptr, guint64* cint); WS_DLL_PUBLIC gboolean ws_hexstrtou32(const gchar* str, const gchar** endptr, guint32* cint); WS_DLL_PUBLIC gboolean ws_hexstrtou16(const gchar* str, const gchar** endptr, guint16* cint); WS_DLL_PUBLIC gboolean ws_hexstrtou8 (const gchar* str, const gchar** endptr, guint8* cint); WS_DLL_PUBLIC gboolean ws_hexstrtou (const gchar* str, const gchar** endptr, guint* cint); /* * \brief Convert a string in the specified base to an unsigned int, with * error checks. * \param str The string to convert * \param endptr A pointer that will store a pointer to the first invalid * character in str, allowing a number to be parsed even if there is trailing * whitespace. If NULL, then the string is assumed to contain only valid * characters (or it will error out). * \param cint The converted integer * \param base The base for the integer; 0 means "if it begins with 0x, * it's hex, otherwise if it begins with 0, it's octal, otherwise it's * decimal". * \return TRUE if the conversion succeeds, FALSE otherwise. * On error, errno is set to EINVAL for unrecognized input and ERANGE * if the resulting number does not fit in the type. */ WS_DLL_PUBLIC gboolean ws_basestrtou64(const gchar* str, const gchar** endptr, guint64* cint, int base); WS_DLL_PUBLIC gboolean ws_basestrtou32(const gchar* str, const gchar** endptr, guint32* cint, int base); WS_DLL_PUBLIC gboolean ws_basestrtou16(const gchar* str, const gchar** endptr, guint16* cint, int base); WS_DLL_PUBLIC gboolean ws_basestrtou8 (const gchar* str, const gchar** endptr, guint8* cint, int base); WS_DLL_PUBLIC gboolean ws_basestrtou (const gchar* str, const gchar** endptr, guint* cint, int base); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=4 tabstop=8 noexpandtab: * :indentSize=4:tabSize=8:noTabs=false: */
C
wireshark/wsutil/str_util.c
/* str_util.c * String utility routines * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #define _GNU_SOURCE #include "config.h" #include "str_util.h" #include <string.h> #include <ws_codepoints.h> #include <wsutil/to_str.h> static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; gchar * wmem_strconcat(wmem_allocator_t *allocator, const gchar *first, ...) { gsize len; va_list args; gchar *s; gchar *concat; gchar *ptr; if (!first) return NULL; len = 1 + strlen(first); va_start(args, first); while ((s = va_arg(args, gchar*))) { len += strlen(s); } va_end(args); ptr = concat = (gchar *)wmem_alloc(allocator, len); ptr = g_stpcpy(ptr, first); va_start(args, first); while ((s = va_arg(args, gchar*))) { ptr = g_stpcpy(ptr, s); } va_end(args); return concat; } gchar * wmem_strjoin(wmem_allocator_t *allocator, const gchar *separator, const gchar *first, ...) { gsize len; va_list args; gsize separator_len; gchar *s; gchar *concat; gchar *ptr; if (!first) return NULL; if (separator == NULL) { separator = ""; } separator_len = strlen (separator); len = 1 + strlen(first); /* + 1 for null byte */ va_start(args, first); while ((s = va_arg(args, gchar*))) { len += (separator_len + strlen(s)); } va_end(args); ptr = concat = (gchar *)wmem_alloc(allocator, len); ptr = g_stpcpy(ptr, first); va_start(args, first); while ((s = va_arg(args, gchar*))) { ptr = g_stpcpy(ptr, separator); ptr = g_stpcpy(ptr, s); } va_end(args); return concat; } gchar * wmem_strjoinv(wmem_allocator_t *allocator, const gchar *separator, gchar **str_array) { gchar *string = NULL; if (!str_array) return NULL; if (separator == NULL) { separator = ""; } if (str_array[0]) { gint i; gchar *ptr; gsize len, separator_len; separator_len = strlen(separator); /* Get first part of length. Plus one for null byte. */ len = 1 + strlen(str_array[0]); /* Get the full length, including the separators. */ for (i = 1; str_array[i] != NULL; i++) { len += separator_len; len += strlen(str_array[i]); } /* Allocate and build the string. */ string = (gchar *)wmem_alloc(allocator, len); ptr = g_stpcpy(string, str_array[0]); for (i = 1; str_array[i] != NULL; i++) { ptr = g_stpcpy(ptr, separator); ptr = g_stpcpy(ptr, str_array[i]); } } return string; } gchar ** wmem_strsplit(wmem_allocator_t *allocator, const gchar *src, const gchar *delimiter, int max_tokens) { gchar *splitted; gchar *s; guint tokens; guint sep_len; guint i; gchar **vec; if (!src || !delimiter || !delimiter[0]) return NULL; /* An empty string results in an empty vector. */ if (!src[0]) { vec = wmem_new0(allocator, gchar *); return vec; } splitted = wmem_strdup(allocator, src); sep_len = (guint)strlen(delimiter); if (max_tokens < 1) max_tokens = INT_MAX; /* Calculate the number of fields. */ s = splitted; tokens = 1; while (tokens < (guint)max_tokens && (s = strstr(s, delimiter))) { s += sep_len; tokens++; } vec = wmem_alloc_array(allocator, gchar *, tokens + 1); /* Populate the array of string tokens. */ s = splitted; vec[0] = s; tokens = 1; while (tokens < (guint)max_tokens && (s = strstr(s, delimiter))) { for (i = 0; i < sep_len; i++) s[i] = '\0'; s += sep_len; vec[tokens] = s; tokens++; } vec[tokens] = NULL; return vec; } /* * wmem_ascii_strdown: * based on g_ascii_strdown. */ gchar* wmem_ascii_strdown(wmem_allocator_t *allocator, const gchar *str, gssize len) { gchar *result, *s; g_return_val_if_fail (str != NULL, NULL); if (len < 0) len = strlen (str); result = wmem_strndup(allocator, str, len); for (s = result; *s; s++) *s = g_ascii_tolower (*s); return result; } int ws_xton(char ch) { switch (ch) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return -1; } } /* Convert all ASCII letters to lower case, in place. */ gchar * ascii_strdown_inplace(gchar *str) { gchar *s; for (s = str; *s; s++) /* What 'g_ascii_tolower (gchar c)' does, this should be slightly more efficient */ *s = g_ascii_isupper (*s) ? *s - 'A' + 'a' : *s; return (str); } /* Convert all ASCII letters to upper case, in place. */ gchar * ascii_strup_inplace(gchar *str) { gchar *s; for (s = str; *s; s++) /* What 'g_ascii_toupper (gchar c)' does, this should be slightly more efficient */ *s = g_ascii_islower (*s) ? *s - 'a' + 'A' : *s; return (str); } /* Check if an entire string is printable. */ gboolean isprint_string(const gchar *str) { guint pos; /* Loop until we reach the end of the string (a null) */ for(pos = 0; str[pos] != '\0'; pos++){ if(!g_ascii_isprint(str[pos])){ /* The string contains a non-printable character */ return FALSE; } } /* The string contains only printable characters */ return TRUE; } /* Check if an entire UTF-8 string is printable. */ gboolean isprint_utf8_string(const gchar *str, const guint length) { const gchar *strend = str + length; if (!g_utf8_validate(str, length, NULL)) { return FALSE; } while (str < strend) { /* This returns false for G_UNICODE_CONTROL | G_UNICODE_FORMAT | * G_UNICODE_UNASSIGNED | G_UNICODE_SURROGATE * XXX: Could it be ok to have certain format characters, e.g. * U+00AD SOFT HYPHEN? If so, format_text() should be changed too. */ if (!g_unichar_isprint(g_utf8_get_char(str))) { return FALSE; } str = g_utf8_next_char(str); } return TRUE; } /* Check if an entire string is digits. */ gboolean isdigit_string(const guchar *str) { guint pos; /* Loop until we reach the end of the string (a null) */ for(pos = 0; str[pos] != '\0'; pos++){ if(!g_ascii_isdigit(str[pos])){ /* The string contains a non-digit character */ return FALSE; } } /* The string contains only digits */ return TRUE; } const char * ws_strcasestr(const char *haystack, const char *needle) { #ifdef HAVE_STRCASESTR return strcasestr(haystack, needle); #else gsize hlen = strlen(haystack); gsize nlen = strlen(needle); while (hlen-- >= nlen) { if (!g_ascii_strncasecmp(haystack, needle, nlen)) return haystack; haystack++; } return NULL; #endif /* HAVE_STRCASESTR */ } #define FORMAT_SIZE_UNIT_MASK 0x00ff #define FORMAT_SIZE_PFX_MASK 0xff00 static const char *thousands_grouping_fmt = NULL; DIAG_OFF(format) static void test_printf_thousands_grouping(void) { /* test whether wmem_strbuf works with "'" flag character */ wmem_strbuf_t *buf = wmem_strbuf_new(NULL, NULL); wmem_strbuf_append_printf(buf, "%'d", 22); if (g_strcmp0(wmem_strbuf_get_str(buf), "22") == 0) { thousands_grouping_fmt = "%'"PRId64; } else { /* Don't use */ thousands_grouping_fmt = "%"PRId64; } wmem_strbuf_destroy(buf); } DIAG_ON(format) /* Given a size, return its value in a human-readable format */ /* This doesn't handle fractional values. We might want to make size a double. */ char * format_size_wmem(wmem_allocator_t *allocator, int64_t size, format_size_units_e unit, uint16_t flags) { wmem_strbuf_t *human_str = wmem_strbuf_new(allocator, NULL); int power = 1000; int pfx_off = 0; gboolean is_small = FALSE; static const gchar *prefix[] = {" T", " G", " M", " k", " Ti", " Gi", " Mi", " Ki"}; gchar *ret_val; if (thousands_grouping_fmt == NULL) test_printf_thousands_grouping(); if (flags & FORMAT_SIZE_PREFIX_IEC) { pfx_off = 4; power = 1024; } if (size / power / power / power / power >= 10) { wmem_strbuf_append_printf(human_str, thousands_grouping_fmt, size / power / power / power / power); wmem_strbuf_append(human_str, prefix[pfx_off]); } else if (size / power / power / power >= 10) { wmem_strbuf_append_printf(human_str, thousands_grouping_fmt, size / power / power / power); wmem_strbuf_append(human_str, prefix[pfx_off+1]); } else if (size / power / power >= 10) { wmem_strbuf_append_printf(human_str, thousands_grouping_fmt, size / power / power); wmem_strbuf_append(human_str, prefix[pfx_off+2]); } else if (size / power >= 10) { wmem_strbuf_append_printf(human_str, thousands_grouping_fmt, size / power); wmem_strbuf_append(human_str, prefix[pfx_off+3]); } else { wmem_strbuf_append_printf(human_str, thousands_grouping_fmt, size); is_small = TRUE; } switch (unit) { case FORMAT_SIZE_UNIT_NONE: break; case FORMAT_SIZE_UNIT_BYTES: wmem_strbuf_append(human_str, is_small ? " bytes" : "B"); break; case FORMAT_SIZE_UNIT_BITS: wmem_strbuf_append(human_str, is_small ? " bits" : "b"); break; case FORMAT_SIZE_UNIT_BITS_S: wmem_strbuf_append(human_str, is_small ? " bits/s" : "bps"); break; case FORMAT_SIZE_UNIT_BYTES_S: wmem_strbuf_append(human_str, is_small ? " bytes/s" : "Bps"); break; case FORMAT_SIZE_UNIT_PACKETS: wmem_strbuf_append(human_str, is_small ? " packets" : "packets"); break; case FORMAT_SIZE_UNIT_PACKETS_S: wmem_strbuf_append(human_str, is_small ? " packets/s" : "packets/s"); break; default: ws_assert_not_reached(); } ret_val = wmem_strbuf_finalize(human_str); return g_strchomp(ret_val); } gchar printable_char_or_period(gchar c) { return g_ascii_isprint(c) ? c : '.'; } /* * This is used by the display filter engine and must be compatible * with display filter syntax. */ static inline bool escape_char(char c, char *p) { int r = -1; ws_assert(p); /* * Backslashes and double-quotes must * be escaped. Whitespace is also escaped. */ switch (c) { case '\a': r = 'a'; break; case '\b': r = 'b'; break; case '\f': r = 'f'; break; case '\n': r = 'n'; break; case '\r': r = 'r'; break; case '\t': r = 't'; break; case '\v': r = 'v'; break; case '"': r = '"'; break; case '\\': r = '\\'; break; case '\0': r = '0'; break; } if (r != -1) { *p = r; return true; } return false; } static inline bool escape_null(char c, char *p) { ws_assert(p); if (c == '\0') { *p = '0'; return true; } return false; } static char * escape_string_len(wmem_allocator_t *alloc, const char *string, ssize_t len, bool (*escape_func)(char c, char *p), bool add_quotes) { char c, r; wmem_strbuf_t *buf; size_t alloc_size; ssize_t i; if (len < 0) len = strlen(string); alloc_size = len; if (add_quotes) alloc_size += 2; buf = wmem_strbuf_new_sized(alloc, alloc_size); if (add_quotes) wmem_strbuf_append_c(buf, '"'); for (i = 0; i < len; i++) { c = string[i]; if ((escape_func(c, &r))) { wmem_strbuf_append_c(buf, '\\'); wmem_strbuf_append_c(buf, r); } else { /* Other UTF-8 bytes are passed through. */ wmem_strbuf_append_c(buf, c); } } if (add_quotes) wmem_strbuf_append_c(buf, '"'); return wmem_strbuf_finalize(buf); } char * ws_escape_string_len(wmem_allocator_t *alloc, const char *string, ssize_t len, bool add_quotes) { return escape_string_len(alloc, string, len, escape_char, add_quotes); } char * ws_escape_string(wmem_allocator_t *alloc, const char *string, bool add_quotes) { return escape_string_len(alloc, string, -1, escape_char, add_quotes); } char *ws_escape_null(wmem_allocator_t *alloc, const char *string, size_t len, bool add_quotes) { return escape_string_len(alloc, string, len, escape_null, add_quotes); } const char * ws_strerrorname_r(int errnum, char *buf, size_t buf_size) { #ifdef HAVE_STRERRORNAME_NP const char *errstr = strerrorname_np(errnum); if (errstr != NULL) { (void)g_strlcpy(buf, errstr, buf_size); return buf; } #endif snprintf(buf, buf_size, "Errno(%d)", errnum); return buf; } char * ws_strdup_underline(wmem_allocator_t *allocator, long offset, size_t len) { if (offset < 0) return NULL; wmem_strbuf_t *buf = wmem_strbuf_new_sized(allocator, offset + len); for (int i = 0; i < offset; i++) { wmem_strbuf_append_c(buf, ' '); } wmem_strbuf_append_c(buf, '^'); for (size_t l = len; l > 1; l--) { wmem_strbuf_append_c(buf, '~'); } return wmem_strbuf_finalize(buf); } #define INITIAL_FMTBUF_SIZE 128 /* * Declare, and initialize, the variables used for an output buffer. */ #define FMTBUF_VARS \ gchar *fmtbuf = (gchar*)wmem_alloc(allocator, INITIAL_FMTBUF_SIZE); \ guint fmtbuf_len = INITIAL_FMTBUF_SIZE; \ guint column = 0 /* * Expand the buffer to be large enough to add nbytes bytes, plus a * terminating '\0'. */ #define FMTBUF_EXPAND(nbytes) \ /* \ * Is there enough room for those bytes and also enough room for \ * a terminating '\0'? \ */ \ if (column+(nbytes+1) >= fmtbuf_len) { \ /* \ * Double the buffer's size if it's not big enough. \ * The size of the buffer starts at 128, so doubling its size \ * adds at least another 128 bytes, which is more than enough \ * for one more character plus a terminating '\0'. \ */ \ fmtbuf_len *= 2; \ fmtbuf = (gchar *)wmem_realloc(allocator, fmtbuf, fmtbuf_len); \ } /* * Put a byte into the buffer; space must have been ensured for it. */ #define FMTBUF_PUTCHAR(b) \ fmtbuf[column] = (b); \ column++ /* * Add the one-byte argument, as an octal escape sequence, to the end * of the buffer. */ #define FMTBUF_PUTBYTE_OCTAL(b) \ FMTBUF_PUTCHAR((((b)>>6)&03) + '0'); \ FMTBUF_PUTCHAR((((b)>>3)&07) + '0'); \ FMTBUF_PUTCHAR((((b)>>0)&07) + '0') /* * Add the one-byte argument, as a hex escape sequence, to the end * of the buffer. */ #define FMTBUF_PUTBYTE_HEX(b) \ FMTBUF_PUTCHAR('\\'); \ FMTBUF_PUTCHAR('x'); \ FMTBUF_PUTCHAR(hex[((b) >> 4) & 0xF]); \ FMTBUF_PUTCHAR(hex[((b) >> 0) & 0xF]) /* * Put the trailing '\0' at the end of the buffer. */ #define FMTBUF_ENDSTR \ fmtbuf[column] = '\0' static gchar * format_text_internal(wmem_allocator_t *allocator, const guchar *string, size_t len, gboolean replace_space) { FMTBUF_VARS; const guchar *stringend = string + len; guchar c; while (string < stringend) { /* * Get the first byte of this character. */ c = *string++; if (g_ascii_isprint(c)) { /* * Printable ASCII, so not part of a multi-byte UTF-8 sequence. * Make sure there's enough room for one more byte, and add * the character. */ FMTBUF_EXPAND(1); FMTBUF_PUTCHAR(c); } else if (replace_space && g_ascii_isspace(c)) { /* * ASCII, so not part of a multi-byte UTF-8 sequence, but * not printable, but is a space character; show it as a * blank. * * Make sure there's enough room for one more byte, and add * the blank. */ FMTBUF_EXPAND(1); FMTBUF_PUTCHAR(' '); } else if (c < 128) { /* * ASCII, so not part of a multi-byte UTF-8 sequence, but not * printable. * * That requires a minimum of 2 bytes, one for the backslash * and one for a letter, so make sure we have enough room * for that, plus a trailing '\0'. */ FMTBUF_EXPAND(2); FMTBUF_PUTCHAR('\\'); switch (c) { case '\a': FMTBUF_PUTCHAR('a'); break; case '\b': FMTBUF_PUTCHAR('b'); /* BS */ break; case '\f': FMTBUF_PUTCHAR('f'); /* FF */ break; case '\n': FMTBUF_PUTCHAR('n'); /* NL */ break; case '\r': FMTBUF_PUTCHAR('r'); /* CR */ break; case '\t': FMTBUF_PUTCHAR('t'); /* tab */ break; case '\v': FMTBUF_PUTCHAR('v'); break; default: /* * We've already put the backslash, but this * will put 3 more characters for the octal * number; make sure we have enough room for * that, plus the trailing '\0'. */ FMTBUF_EXPAND(3); FMTBUF_PUTBYTE_OCTAL(c); break; } } else { /* * We've fetched the first byte of a multi-byte UTF-8 * sequence into c. */ int utf8_len; guchar mask; gunichar uc; guchar first; if ((c & 0xe0) == 0xc0) { /* Starts a 2-byte UTF-8 sequence; 1 byte left */ utf8_len = 1; mask = 0x1f; } else if ((c & 0xf0) == 0xe0) { /* Starts a 3-byte UTF-8 sequence; 2 bytes left */ utf8_len = 2; mask = 0x0f; } else if ((c & 0xf8) == 0xf0) { /* Starts a 4-byte UTF-8 sequence; 3 bytes left */ utf8_len = 3; mask = 0x07; } else if ((c & 0xfc) == 0xf8) { /* Starts an old-style 5-byte UTF-8 sequence; 4 bytes left */ utf8_len = 4; mask = 0x03; } else if ((c & 0xfe) == 0xfc) { /* Starts an old-style 6-byte UTF-8 sequence; 5 bytes left */ utf8_len = 5; mask = 0x01; } else { /* 0xfe or 0xff or a continuation byte - not valid */ utf8_len = -1; } if (utf8_len > 0) { /* Try to construct the Unicode character */ uc = c & mask; for (int i = 0; i < utf8_len; i++) { if (string >= stringend) { /* * Ran out of octets, so the character is * incomplete. Put in a REPLACEMENT CHARACTER * instead, and then continue the loop, which * will terminate. */ uc = UNICODE_REPLACEMENT_CHARACTER; break; } c = *string; if ((c & 0xc0) != 0x80) { /* * Not valid UTF-8 continuation character; put in * a replacement character, and then re-process * this octet as the beginning of a new character. */ uc = UNICODE_REPLACEMENT_CHARACTER; break; } string++; uc = (uc << 6) | (c & 0x3f); } /* * If this isn't a valid Unicode character, put in * a REPLACEMENT CHARACTER. */ if (!g_unichar_validate(uc)) uc = UNICODE_REPLACEMENT_CHARACTER; } else { /* 0xfe or 0xff; put it a REPLACEMENT CHARACTER */ uc = UNICODE_REPLACEMENT_CHARACTER; } /* * OK, is it a printable Unicode character? */ if (g_unichar_isprint(uc)) { /* * Yes - put it into the string as UTF-8. * This means that if it was an overlong * encoding, this will put out the right * sized encoding. */ if (uc < 0x80) { first = 0; utf8_len = 1; } else if (uc < 0x800) { first = 0xc0; utf8_len = 2; } else if (uc < 0x10000) { first = 0xe0; utf8_len = 3; } else if (uc < 0x200000) { first = 0xf0; utf8_len = 4; } else if (uc < 0x4000000) { /* * This should never happen, as Unicode doesn't * go that high. */ first = 0xf8; utf8_len = 5; } else { /* * This should never happen, as Unicode doesn't * go that high. */ first = 0xfc; utf8_len = 6; } FMTBUF_EXPAND(utf8_len); for (int i = utf8_len - 1; i > 0; i--) { fmtbuf[column + i] = (uc & 0x3f) | 0x80; uc >>= 6; } fmtbuf[column] = uc | first; column += utf8_len; } else if (replace_space && g_unichar_isspace(uc)) { /* * Not printable, but is a space character; show it * as a blank. * * Make sure there's enough room for one more byte, * and add the blank. */ FMTBUF_EXPAND(1); FMTBUF_PUTCHAR(' '); } else if (c < 128) { /* * ASCII, but not printable. * Yes, this could happen with an overlong encoding. * * That requires a minimum of 2 bytes, one for the * backslash and one for a letter, so make sure we * have enough room for that, plus a trailing '\0'. */ FMTBUF_EXPAND(2); FMTBUF_PUTCHAR('\\'); switch (c) { case '\a': FMTBUF_PUTCHAR('a'); break; case '\b': FMTBUF_PUTCHAR('b'); /* BS */ break; case '\f': FMTBUF_PUTCHAR('f'); /* FF */ break; case '\n': FMTBUF_PUTCHAR('n'); /* NL */ break; case '\r': FMTBUF_PUTCHAR('r'); /* CR */ break; case '\t': FMTBUF_PUTCHAR('t'); /* tab */ break; case '\v': FMTBUF_PUTCHAR('v'); break; default: /* * We've already put the backslash, but this * will put 3 more characters for the octal * number; make sure we have enough room for * that, plus the trailing '\0'. */ FMTBUF_EXPAND(3); FMTBUF_PUTBYTE_OCTAL(c); break; } } else { /* * Unicode, but not printable, and not ASCII; * put it out as \uxxxx or \Uxxxxxxxx. */ if (uc <= 0xFFFF) { FMTBUF_EXPAND(6); FMTBUF_PUTCHAR('\\'); FMTBUF_PUTCHAR('u'); FMTBUF_PUTCHAR(hex[(uc >> 12) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 8) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 4) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 0) & 0xF]); } else { FMTBUF_EXPAND(10); FMTBUF_PUTCHAR('\\'); FMTBUF_PUTCHAR('U'); FMTBUF_PUTCHAR(hex[(uc >> 28) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 24) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 20) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 16) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 12) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 8) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 4) & 0xF]); FMTBUF_PUTCHAR(hex[(uc >> 0) & 0xF]); } } } } FMTBUF_ENDSTR; return fmtbuf; } /* * Given a wmem scope, a not-necessarily-null-terminated string, * expected to be in UTF-8 but possibly containing invalid sequences * (as it may have come from packet data), and the length of the string, * generate a valid UTF-8 string from it, allocated in the specified * wmem scope, that: * * shows printable Unicode characters as themselves; * * shows non-printable ASCII characters as C-style escapes (octal * if not one of the standard ones such as LF -> '\n'); * * shows non-printable Unicode-but-not-ASCII characters as * their universal character names; * * shows illegal UTF-8 sequences as a sequence of bytes represented * as C-style hex escapes (XXX: Does not actually do this. Some illegal * sequences, such as overlong encodings, the sequences reserved for * UTF-16 surrogate halves (paired or unpaired), and values outside * Unicode (i.e., the old sequences for code points above U+10FFFF) * will be decoded in a permissive way. Other illegal sequences, * such 0xFE and 0xFF and the presence of a continuation byte where * not expected (or vice versa its absence), are replaced with * REPLACEMENT CHARACTER.) * * and return a pointer to it. */ char * format_text(wmem_allocator_t *allocator, const char *string, size_t len) { return format_text_internal(allocator, string, len, FALSE); } /** Given a wmem scope and a null-terminated string, expected to be in * UTF-8 but possibly containing invalid sequences (as it may have come * from packet data), and the length of the string, generate a valid * UTF-8 string from it, allocated in the specified wmem scope, that: * * shows printable Unicode characters as themselves; * * shows non-printable ASCII characters as C-style escapes (octal * if not one of the standard ones such as LF -> '\n'); * * shows non-printable Unicode-but-not-ASCII characters as * their universal character names; * * shows illegal UTF-8 sequences as a sequence of bytes represented * as C-style hex escapes; * * and return a pointer to it. */ char * format_text_string(wmem_allocator_t* allocator, const char *string) { return format_text_internal(allocator, string, strlen(string), FALSE); } /* * Given a string, generate a string from it that shows non-printable * characters as C-style escapes except a whitespace character * (space, tab, carriage return, new line, vertical tab, or formfeed) * which will be replaced by a space, and return a pointer to it. */ char * format_text_wsp(wmem_allocator_t* allocator, const char *string, size_t len) { return format_text_internal(allocator, string, len, TRUE); } /* * Given a string, generate a string from it that shows non-printable * characters as the chr parameter passed, except a whitespace character * (space, tab, carriage return, new line, vertical tab, or formfeed) * which will be replaced by a space, and return a pointer to it. * * This does *not* treat the input string as UTF-8. * * This is useful for displaying binary data that frequently but not always * contains text; otherwise the number of C escape codes makes it unreadable. */ char * format_text_chr(wmem_allocator_t *allocator, const char *string, size_t len, char chr) { wmem_strbuf_t *buf; buf = wmem_strbuf_new_sized(allocator, len + 1); for (const char *p = string; p < string + len; p++) { if (g_ascii_isprint(*p)) { wmem_strbuf_append_c(buf, *p); } else if (g_ascii_isspace(*p)) { wmem_strbuf_append_c(buf, ' '); } else { wmem_strbuf_append_c(buf, chr); } } return wmem_strbuf_finalize(buf); } char * format_char(wmem_allocator_t *allocator, char c) { char *buf; char r; if (g_ascii_isprint(c)) { buf = wmem_alloc_array(allocator, char, 2); buf[0] = c; buf[1] = '\0'; return buf; } if (escape_char(c, &r)) { buf = wmem_alloc_array(allocator, char, 3); buf[0] = '\\'; buf[1] = r; buf[2] = '\0'; return buf; } buf = wmem_alloc_array(allocator, char, 5); buf[0] = '\\'; buf[1] = 'x'; buf[2] = hex[((uint8_t)c >> 4) & 0xF]; buf[3] = hex[((uint8_t)c >> 0) & 0xF]; buf[4] = '\0'; return buf; } char* ws_utf8_truncate(char *string, size_t len) { char* last_char; /* Ensure that it is null terminated */ string[len] = '\0'; last_char = g_utf8_find_prev_char(string, string + len); if (last_char != NULL && g_utf8_get_char_validated(last_char, -1) == (gunichar)-2) { /* The last UTF-8 character was truncated into a partial sequence. */ *last_char = '\0'; } return string; } /* ASCII/EBCDIC conversion tables from * https://web.archive.org/web/20060813174742/http://www.room42.com/store/computer_center/code_tables.shtml */ #if 0 static const guint8 ASCII_translate_EBCDIC [ 256 ] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D, 0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F, 0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x5F, 0x6D, 0x7D, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xC0, 0x6A, 0xD0, 0xA1, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B }; void ASCII_to_EBCDIC(guint8 *buf, guint bytes) { guint i; guint8 *bufptr; bufptr = buf; for (i = 0; i < bytes; i++, bufptr++) { *bufptr = ASCII_translate_EBCDIC[*bufptr]; } } guint8 ASCII_to_EBCDIC1(guint8 c) { return ASCII_translate_EBCDIC[c]; } #endif static const guint8 EBCDIC_translate_ASCII [ 256 ] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x2E, 0x2E, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x2E, 0x3F, 0x20, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x3C, 0x28, 0x2B, 0x7C, 0x26, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0x5E, 0x2D, 0x2F, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x7C, 0x2C, 0x25, 0x5F, 0x3E, 0x3F, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22, 0x2E, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x2E, 0x2E, 0x2E, 0x5B, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x5D, 0x2E, 0x2E, 0x7B, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x7D, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x5C, 0x2E, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E }; void EBCDIC_to_ASCII(guint8 *buf, guint bytes) { guint i; guint8 *bufptr; bufptr = buf; for (i = 0; i < bytes; i++, bufptr++) { *bufptr = EBCDIC_translate_ASCII[*bufptr]; } } guint8 EBCDIC_to_ASCII1(guint8 c) { return EBCDIC_translate_ASCII[c]; } /* * This routine is based on a routine created by Dan Lasley * <[email protected]>. * * It was modified for Wireshark by Gilbert Ramirez and others. */ #define MAX_OFFSET_LEN 8 /* max length of hex offset of bytes */ #define BYTES_PER_LINE 16 /* max byte values printed on a line */ #define HEX_DUMP_LEN (BYTES_PER_LINE*3) /* max number of characters hex dump takes - 2 digits plus trailing blank */ #define DATA_DUMP_LEN (HEX_DUMP_LEN + 2 + 2 + BYTES_PER_LINE) /* number of characters those bytes take; 3 characters per byte of hex dump, 2 blanks separating hex from ASCII, 2 optional ASCII dump delimiters, 1 character per byte of ASCII dump */ #define MAX_LINE_LEN (MAX_OFFSET_LEN + 2 + DATA_DUMP_LEN) /* number of characters per line; offset, 2 blanks separating offset from data dump, data dump */ gboolean hex_dump_buffer(gboolean (*print_line)(void *, const char *), void *fp, const guchar *cp, guint length, hex_dump_enc encoding, guint ascii_option) { register unsigned int ad, i, j, k, l; guchar c; gchar line[MAX_LINE_LEN + 1]; unsigned int use_digits; static gchar binhex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; /* * How many of the leading digits of the offset will we supply? * We always supply at least 4 digits, but if the maximum offset * won't fit in 4 digits, we use as many digits as will be needed. */ if (((length - 1) & 0xF0000000) != 0) use_digits = 8; /* need all 8 digits */ else if (((length - 1) & 0x0F000000) != 0) use_digits = 7; /* need 7 digits */ else if (((length - 1) & 0x00F00000) != 0) use_digits = 6; /* need 6 digits */ else if (((length - 1) & 0x000F0000) != 0) use_digits = 5; /* need 5 digits */ else use_digits = 4; /* we'll supply 4 digits */ ad = 0; i = 0; j = 0; k = 0; while (i < length) { if ((i & 15) == 0) { /* * Start of a new line. */ j = 0; l = use_digits; do { l--; c = (ad >> (l*4)) & 0xF; line[j++] = binhex[c]; } while (l != 0); line[j++] = ' '; line[j++] = ' '; memset(line+j, ' ', DATA_DUMP_LEN); /* * Offset in line of ASCII dump. */ k = j + HEX_DUMP_LEN + 2; if (ascii_option == HEXDUMP_ASCII_DELIMIT) line[k++] = '|'; } c = *cp++; line[j++] = binhex[c>>4]; line[j++] = binhex[c&0xf]; j++; if (ascii_option != HEXDUMP_ASCII_EXCLUDE ) { if (encoding == HEXDUMP_ENC_EBCDIC) { c = EBCDIC_to_ASCII1(c); } line[k++] = ((c >= ' ') && (c < 0x7f)) ? c : '.'; } i++; if (((i & 15) == 0) || (i == length)) { /* * We'll be starting a new line, or * we're finished printing this buffer; * dump out the line we've constructed, * and advance the offset. */ if (ascii_option == HEXDUMP_ASCII_DELIMIT) line[k++] = '|'; line[k] = '\0'; if (!print_line(fp, line)) return FALSE; ad += 16; } } return TRUE; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/str_util.h
/** @file * String utility definitions * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __STR_UTIL_H__ #define __STR_UTIL_H__ #include <wireshark.h> #include <wsutil/wmem/wmem.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ WS_DLL_PUBLIC gchar * wmem_strconcat(wmem_allocator_t *allocator, const gchar *first, ...) G_GNUC_MALLOC G_GNUC_NULL_TERMINATED; WS_DLL_PUBLIC gchar * wmem_strjoin(wmem_allocator_t *allocator, const gchar *separator, const gchar *first, ...) G_GNUC_MALLOC G_GNUC_NULL_TERMINATED; WS_DLL_PUBLIC gchar * wmem_strjoinv(wmem_allocator_t *allocator, const gchar *separator, gchar **str_array) G_GNUC_MALLOC; /** * Splits a string into a maximum of max_tokens pieces, using the given * delimiter. If max_tokens is reached, the remainder of string is appended * to the last token. Successive tokens are not folded and will instead result * in an empty string as element. * * If src or delimiter are NULL, or if delimiter is empty, this will return * NULL. * * Do not use with a NULL allocator, use g_strsplit instead. */ WS_DLL_PUBLIC gchar ** wmem_strsplit(wmem_allocator_t *allocator, const gchar *src, const gchar *delimiter, int max_tokens); /** * wmem_ascii_strdown: * Based on g_ascii_strdown * @param allocator An enumeration of the different types of available allocators. * @param str a string. * @param len length of str in bytes, or -1 if str is nul-terminated. * * Converts all upper case ASCII letters to lower case ASCII letters. * * Return value: a newly-allocated string, with all the upper case * characters in str converted to lower case, with * semantics that exactly match g_ascii_tolower(). (Note * that this is unlike the old g_strdown(), which modified * the string in place.) **/ WS_DLL_PUBLIC gchar* wmem_ascii_strdown(wmem_allocator_t *allocator, const gchar *str, gssize len); /** Convert all upper-case ASCII letters to their ASCII lower-case * equivalents, in place, with a simple non-locale-dependent * ASCII mapping (A-Z -> a-z). * All other characters are left unchanged, as the mapping to * lower case may be locale-dependent. * * The string is assumed to be in a character encoding, such as * an ISO 8859 or other EUC encoding, or UTF-8, in which all * bytes in the range 0x00 through 0x7F are ASCII characters and * non-ASCII characters are constructed from one or more bytes in * the range 0x80 through 0xFF. * * @param str The string to be lower-cased. * @return ptr to the string */ WS_DLL_PUBLIC gchar *ascii_strdown_inplace(gchar *str); /** Convert all lower-case ASCII letters to their ASCII upper-case * equivalents, in place, with a simple non-locale-dependent * ASCII mapping (a-z -> A-Z). * All other characters are left unchanged, as the mapping to * lower case may be locale-dependent. * * The string is assumed to be in a character encoding, such as * an ISO 8859 or other EUC encoding, or UTF-8, in which all * bytes in the range 0x00 through 0x7F are ASCII characters and * non-ASCII characters are constructed from one or more bytes in * the range 0x80 through 0xFF. * * @param str The string to be upper-cased. * @return ptr to the string */ WS_DLL_PUBLIC gchar *ascii_strup_inplace(gchar *str); /** Check if an entire string consists of printable characters * * @param str The string to be checked * @return TRUE if the entire string is printable, otherwise FALSE */ WS_DLL_PUBLIC gboolean isprint_string(const gchar *str); /** Given a not-necessarily-null-terminated string, expected to be in * UTF-8 but possibly containing invalid sequences (as it may have come * from packet data), and the length of the string, deterimine if the * string is valid UTF-8 consisting entirely of printable characters. * * This means that it: * * does not contain an illegal UTF-8 sequence (including overlong encodings, * the sequences reserved for UTF-16 surrogate halves, and the values for * code points above U+10FFFF that are no longer in Unicode) * * does not contain a non-printable Unicode character such as control * characters (including internal NULL bytes) * * does not end in a partial sequence that could begin a valid character; * * does not start with a partial sequence that could end a valid character; * * and thus guarantees that the result of format_text() would be the same as * that of wmem_strndup() with the same parameters. * * @param str The string to be checked * @param length The number of bytes to validate * @return TRUE if the entire string is valid and printable UTF-8, * otherwise FALSE */ WS_DLL_PUBLIC gboolean isprint_utf8_string(const gchar *str, const guint length); /** Check if an entire string consists of digits * * @param str The string to be checked * @return TRUE if the entire string is digits, otherwise FALSE */ WS_DLL_PUBLIC gboolean isdigit_string(const guchar *str); /** Finds the first occurrence of string 'needle' in string 'haystack'. * The matching is done in a case insensitive manner. * * @param haystack The string possibly containing the substring * @param needle The substring to be searched * @return A pointer into 'haystack' where 'needle' is first found. * Otherwise it returns NULL. */ WS_DLL_PUBLIC const char *ws_strcasestr(const char *haystack, const char *needle); WS_DLL_PUBLIC char *ws_escape_string(wmem_allocator_t *alloc, const char *string, bool add_quotes); WS_DLL_PUBLIC char *ws_escape_string_len(wmem_allocator_t *alloc, const char *string, ssize_t len, bool add_quotes); /* Replace null bytes with "\0". */ WS_DLL_PUBLIC char *ws_escape_null(wmem_allocator_t *alloc, const char *string, size_t len, bool add_quotes); WS_DLL_PUBLIC int ws_xton(char ch); typedef enum { FORMAT_SIZE_UNIT_NONE, /**< No unit will be appended. You must supply your own. */ FORMAT_SIZE_UNIT_BYTES, /**< "bytes" for un-prefixed sizes, "B" otherwise. */ FORMAT_SIZE_UNIT_BITS, /**< "bits" for un-prefixed sizes, "b" otherwise. */ FORMAT_SIZE_UNIT_BITS_S, /**< "bits/s" for un-prefixed sizes, "bps" otherwise. */ FORMAT_SIZE_UNIT_BYTES_S, /**< "bytes/s" for un-prefixed sizes, "Bps" otherwise. */ FORMAT_SIZE_UNIT_PACKETS, /**< "packets" */ FORMAT_SIZE_UNIT_PACKETS_S, /**< "packets/s" */ } format_size_units_e; #define FORMAT_SIZE_PREFIX_SI (1 << 0) /**< SI (power of 1000) prefixes will be used. */ #define FORMAT_SIZE_PREFIX_IEC (1 << 1) /**< IEC (power of 1024) prefixes will be used. */ /** Given a size, return its value in a human-readable format * * Prefixes up to "T/Ti" (tera, tebi) are currently supported. * * @param size The size value * @param flags Flags to control the output (unit of measurement, * SI vs IEC, etc). Unit and prefix flags may be ORed together. * @return A newly-allocated string representing the value. */ WS_DLL_PUBLIC char *format_size_wmem(wmem_allocator_t *allocator, int64_t size, format_size_units_e unit, uint16_t flags); #define format_size(size, unit, flags) \ format_size_wmem(NULL, size, unit, flags) WS_DLL_PUBLIC gchar printable_char_or_period(gchar c); WS_DLL_PUBLIC WS_RETNONNULL const char *ws_strerrorname_r(int errnum, char *buf, size_t buf_size); WS_DLL_PUBLIC char *ws_strdup_underline(wmem_allocator_t *allocator, long offset, size_t len); /** Given a wmem scope, a not-necessarily-null-terminated string, * expected to be in UTF-8 but possibly containing invalid sequences * (as it may have come from packet data), and the length of the string, * generate a valid UTF-8 string from it, allocated in the specified * wmem scope, that: * * shows printable Unicode characters as themselves; * * shows non-printable ASCII characters as C-style escapes (octal * if not one of the standard ones such as LF -> '\n'); * * shows non-printable Unicode-but-not-ASCII characters as * their universal character names; * * Replaces illegal UTF-8 sequences with U+FFFD (replacement character) ; * * and return a pointer to it. * * @param allocator The wmem scope * @param string A pointer to the input string * @param len The length of the input string * @return A pointer to the formatted string * * @see tvb_format_text() */ WS_DLL_PUBLIC char *format_text(wmem_allocator_t* allocator, const char *string, size_t len); /** Same as format_text() but accepts a nul-terminated string. * * @param allocator The wmem scope * @param string A pointer to the input string * @return A pointer to the formatted string * * @see tvb_format_text() */ WS_DLL_PUBLIC char *format_text_string(wmem_allocator_t* allocator, const char *string); /** * Same as format_text() but replaces any whitespace characters * (space, tab, carriage return, new line, vertical tab, or formfeed) * with a space. * * @param allocator The wmem scope * @param line A pointer to the input string * @param len The length of the input string * @return A pointer to the formatted string * */ WS_DLL_PUBLIC char *format_text_wsp(wmem_allocator_t* allocator, const char *line, size_t len); /** * Given a string, generate a string from it that shows non-printable * characters as the chr parameter passed, except a whitespace character * (space, tab, carriage return, new line, vertical tab, or formfeed) * which will be replaced by a space, and return a pointer to it. * * This does *not* treat the input string as UTF-8. * * This is useful for displaying binary data that frequently but not always * contains text; otherwise the number of C escape codes makes it unreadable. * * @param allocator The wmem scope * @param string A pointer to the input string * @param len The length of the input string * @param chr The character to use to replace non-printable characters * @return A pointer to the formatted string * */ WS_DLL_PUBLIC char *format_text_chr(wmem_allocator_t *allocator, const char *string, size_t len, char chr); /** Given a wmem scope and an 8-bit character * generate a valid UTF-8 string from it, allocated in the specified * wmem scope, that: * * shows printable Unicode characters as themselves; * * shows non-printable ASCII characters as C-style escapes (hex * if not one of the standard ones such as LF -> '\n'); * * and return a pointer to it. * * @param allocator The wmem scope * @param c A character to format * @return A pointer to the formatted string */ WS_DLL_PUBLIC char *format_char(wmem_allocator_t *allocator, char c); /** * Truncate a UTF-8 string in place so that it is no larger than len bytes, * ensuring that the string is null terminated and ends with a complete * character instead of a partial sequence (e.g., possibly truncating up * to 3 additional bytes if the terminal character is 4 bytes long). * * The buffer holding the string must be large enough (at least len + 1 * including the null terminator), and the first len bytes of the buffer * must be a valid UTF-8 string, except for possibly ending in a partial * sequence or not being null terminated. This is a convenience function * that for speed does not check either of those conditions. * * A common use case is when a valid UTF-8 string has been copied into a * buffer of length len+1 via snprintf, strlcpy, or strlcat and truncated, * to ensure that the final UTF-8 character is not a partial sequence. * * @param string A pointer to the input string * @param len The maximum length to truncate to * @return ptr to the string */ WS_DLL_PUBLIC char* ws_utf8_truncate(char *string, size_t len); WS_DLL_PUBLIC void EBCDIC_to_ASCII(guint8 *buf, guint bytes); WS_DLL_PUBLIC guint8 EBCDIC_to_ASCII1(guint8 c); /* Types of character encodings */ typedef enum { HEXDUMP_ENC_ASCII = 0, /* ASCII */ HEXDUMP_ENC_EBCDIC = 1 /* EBCDIC */ } hex_dump_enc; /* * Hexdump options for ASCII: */ #define HEXDUMP_ASCII_MASK (0x0003U) #define HEXDUMP_ASCII_OPTION(option) ((option) & HEXDUMP_ASCII_MASK) #define HEXDUMP_ASCII_INCLUDE (0x0000U) /* include ASCII section no delimiters (legacy tshark behavior) */ #define HEXDUMP_ASCII_DELIMIT (0x0001U) /* include ASCII section with delimiters, useful for reliable detection of last hexdata */ #define HEXDUMP_ASCII_EXCLUDE (0x0002U) /* exclude ASCII section from hexdump reports, if we really don't want or need it */ WS_DLL_PUBLIC gboolean hex_dump_buffer(gboolean (*print_line)(void *, const char *), void *fp, const guchar *cp, guint length, hex_dump_enc encoding, guint ascii_option); /* To pass one of two strings, singular or plural */ #define plurality(d,s,p) ((d) == 1 ? (s) : (p)) #define true_or_false(val) ((val) ? "TRUE" : "FALSE") #define string_or_null(val) ((val) ? (val) : "[NULL]") #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __STR_UTIL_H__ */
C
wireshark/wsutil/tempfile.c
/* tempfile.c * Routines to create temporary files * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "tempfile.h" #include <errno.h> #include "file_util.h" static char * sanitize_prefix(const char *prefix) { if (!prefix) { return NULL; } /* The characters in "delimiters" come from: * https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions. * Add to the list as necessary for other OS's. */ const gchar *delimiters = "<>:\"/\\|?*" "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a" "\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"; /* Sanitize the prefix to resolve bug 7877 */ char *safe_prefx = g_strdup(prefix); safe_prefx = g_strdelimit(safe_prefx, delimiters, '-'); return safe_prefx; } /** * Create a tempfile with the given prefix (e.g. "wireshark"). The path * is created using g_file_open_tmp. * * @param tempdir [in] If not NULL, the directory in which to create the file. * @param namebuf [in,out] If not NULL, receives the full path of the temp file. * Must be freed. * @param pfx [in] A prefix for the temporary file. * @param sfx [in] A file extension for the temporary file. NULL can be passed * if no file extension is needed * @param err [out] Any error returned by g_file_open_tmp. May be NULL * @return The file descriptor of the new tempfile, from mkstemps(). */ int create_tempfile(const char *tempdir, gchar **namebuf, const char *pfx, const char *sfx, GError **err) { int fd; gchar *safe_pfx = sanitize_prefix(pfx); if (tempdir == NULL || tempdir[0] == '\0') { /* Use OS default tempdir behaviour */ gchar* filetmpl = ws_strdup_printf("%sXXXXXX%s", safe_pfx ? safe_pfx : "", sfx ? sfx : ""); g_free(safe_pfx); fd = g_file_open_tmp(filetmpl, namebuf, err); g_free(filetmpl); } else { /* User-specified tempdir. * We don't get libc's help generating a random name here. */ const gchar alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; const gint32 a_len = 64; gchar* filetmpl = NULL; while(1) { g_free(filetmpl); filetmpl = ws_strdup_printf("%s%c%s%c%c%c%c%c%c%s", tempdir, G_DIR_SEPARATOR, safe_pfx ? safe_pfx : "", alphabet[g_random_int_range(0, a_len)], alphabet[g_random_int_range(0, a_len)], alphabet[g_random_int_range(0, a_len)], alphabet[g_random_int_range(0, a_len)], alphabet[g_random_int_range(0, a_len)], alphabet[g_random_int_range(0, a_len)], sfx ? sfx : ""); fd = ws_open(filetmpl, O_CREAT|O_EXCL|O_BINARY|O_WRONLY, 0600); if (fd >= 0) { break; } if (errno != EEXIST) { g_set_error_literal(err, G_FILE_ERROR, g_file_error_from_errno(errno), g_strerror(errno)); g_free(filetmpl); filetmpl = NULL; break; } /* Loop continues if error was EEXIST, meaning the file we tried * to make already existed at the destination */ } if (namebuf == NULL) { g_free(filetmpl); } else { *namebuf = filetmpl; } g_free(safe_pfx); } return fd; } char * create_tempdir(const gchar *parent_dir, const char *tmpl, GError **err) { if (parent_dir == NULL || parent_dir[0] == '\0') { parent_dir = g_get_tmp_dir(); } gchar *safe_pfx = sanitize_prefix(tmpl); if (safe_pfx == NULL) { safe_pfx = g_strdup("wireshark_XXXXXX"); } char *temp_subdir = g_build_path(G_DIR_SEPARATOR_S, parent_dir, safe_pfx, NULL); g_free(safe_pfx); if (g_mkdtemp(temp_subdir) == NULL) { g_free(temp_subdir); g_set_error_literal(err, G_FILE_ERROR, g_file_error_from_errno(errno), g_strerror(errno)); return FALSE; } return temp_subdir; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local Variables: * c-basic-offset: 2 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=2 tabstop=8 expandtab: * :indentSize=2:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/tempfile.h
/* tempfile.h * Declarations of routines to create temporary files * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __TEMPFILE_H__ #define __TEMPFILE_H__ #include <wireshark.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @file * Convenience function for temporary file creation. */ /** * Create a tempfile with the given prefix (e.g. "wireshark"). The path * is created using g_file_open_tmp. * * @param tempdir [in] If not NULL, the directory in which to create the file. * @param namebuf [in,out] If not NULL, receives the full path of the temp file. * Must be g_freed. * @param pfx [in] A prefix for the temporary file. * @param sfx [in] A file extension for the temporary file. NULL can be passed * if no file extension is needed * @param err [out] Any error returned by g_file_open_tmp. May be NULL. * @return The file descriptor of the new tempfile, from mkstemps(). */ WS_DLL_PUBLIC int create_tempfile(const gchar *tempdir, gchar **namebuf, const char *pfx, const char *sfx, GError **err); /** * Create a tempfile with the given parent directory (e.g. "/my/private/tmp"). The path * is created using g_mkdtemp. * * @param parent_dir [in] If not NULL, the parent directory in which to create the subdirectory, * otherwise the system temporary directory is used. * @param tmpl [in] A template for the temporary directory. * @param err [out] Any error returned by g_mkdtemp. May be NULL. * @return The full path of the temporary directory or NULL on error. Must be g_freed. */ WS_DLL_PUBLIC char *create_tempdir(const gchar *parent_dir, const char *tmpl, GError **err); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __TEMPFILE_H__ */
C
wireshark/wsutil/test_wsutil.c
/* * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <stdio.h> #include <glib.h> #include <wsutil/utf8_entities.h> #include <wsutil/time_util.h> #include "inet_addr.h" static void test_inet_pton4_test1(void) { const char *str; bool ok; ws_in4_addr result, expect; str = "198.51.100.200"; expect = g_htonl(3325256904); ok = ws_inet_pton4(str, &result); g_assert_true(ok); g_assert_cmpint(result, ==, expect); } static void test_inet_ntop4_test1(void) { char result[WS_INET_ADDRSTRLEN]; const char *expect, *ptr; ws_in4_addr addr; addr = g_htonl(3325256904); expect = "198.51.100.200"; ptr = ws_inet_ntop4(&addr, result, sizeof(result)); g_assert_true(ptr == result); g_assert_cmpstr(result, ==, expect); } struct in6_test { char str[WS_INET6_ADDRSTRLEN]; ws_in6_addr addr; }; static struct in6_test in6_test1 = { .str = "2001:db8:ffaa:ddbb:1199:2288:3377:1", .addr = { { 0x20, 0x01, 0x0d, 0xb8, 0xff, 0xaa, 0xdd, 0xbb, 0x11, 0x99, 0x22, 0x88, 0x33, 0x77, 0x00, 0x01 } } }; static void test_inet_pton6_test1(void) { bool ok; ws_in6_addr result; ok = ws_inet_pton6(in6_test1.str, &result); g_assert_true(ok); g_assert_cmpmem(&result, sizeof(result), &in6_test1.addr, sizeof(in6_test1.addr)); } static void test_inet_ntop6_test1(void) { char result[WS_INET6_ADDRSTRLEN]; const char *ptr; ptr = ws_inet_ntop6(&in6_test1.addr, result, sizeof(result)); g_assert_true(ptr == result); g_assert_cmpstr(result, ==, in6_test1.str); } #include "str_util.h" static void test_format_size(void) { char *str; str = format_size(10000, FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_SI); g_assert_cmpstr(str, ==, "10 kB"); g_free(str); str = format_size(100000, FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_IEC); g_assert_cmpstr(str, ==, "97 KiB"); g_free(str); str = format_size(20971520, FORMAT_SIZE_UNIT_BITS, FORMAT_SIZE_PREFIX_IEC); g_assert_cmpstr(str, ==, "20 Mib"); g_free(str); } static void test_escape_string(void) { char *buf; buf = ws_escape_string(NULL, "quoted \"\\\" backslash", true); g_assert_cmpstr(buf, ==, "\"quoted \\\"\\\\\\\" backslash\""); wmem_free(NULL, buf); buf = ws_escape_string(NULL, "whitespace \t \n \r \f \v", true); g_assert_cmpstr(buf, ==, "\"whitespace \\t \\n \\r \\f \\v""\""); wmem_free(NULL, buf); const char s1[] = { 'a', 'b', 'c', '\0', 'e', 'f', 'g'}; buf = ws_escape_null(NULL, s1, sizeof(s1), true); g_assert_cmpstr(buf, ==, "\"abc\\0efg\""); wmem_free(NULL, buf); } static void test_strconcat(void) { wmem_allocator_t *allocator; char *new_str; allocator = wmem_allocator_new(WMEM_ALLOCATOR_BLOCK); new_str = wmem_strconcat(allocator, "ABC", NULL); g_assert_cmpstr(new_str, ==, "ABC"); new_str = wmem_strconcat(allocator, "ABC", "DEF", NULL); g_assert_cmpstr(new_str, ==, "ABCDEF"); new_str = wmem_strconcat(allocator, "", "", "ABCDEF", "", "GH", NULL); g_assert_cmpstr(new_str, ==, "ABCDEFGH"); wmem_destroy_allocator(allocator); } static void test_strsplit(void) { wmem_allocator_t *allocator; char **split_str; allocator = wmem_allocator_new(WMEM_ALLOCATOR_BLOCK); split_str = wmem_strsplit(allocator, "A-C", "-", 2); g_assert_cmpstr(split_str[0], ==, "A"); g_assert_cmpstr(split_str[1], ==, "C"); g_assert_null(split_str[2]); split_str = wmem_strsplit(allocator, "A-C", "-", 0); g_assert_cmpstr(split_str[0], ==, "A"); g_assert_cmpstr(split_str[1], ==, "C"); g_assert_null(split_str[2]); split_str = wmem_strsplit(allocator, "--aslkf-asio--asfj-as--", "-", 10); g_assert_cmpstr(split_str[0], ==, ""); g_assert_cmpstr(split_str[1], ==, ""); g_assert_cmpstr(split_str[2], ==, "aslkf"); g_assert_cmpstr(split_str[3], ==, "asio"); g_assert_cmpstr(split_str[4], ==, ""); g_assert_cmpstr(split_str[5], ==, "asfj"); g_assert_cmpstr(split_str[6], ==, "as"); g_assert_cmpstr(split_str[7], ==, ""); g_assert_cmpstr(split_str[8], ==, ""); g_assert_null(split_str[9]); split_str = wmem_strsplit(allocator, "--aslkf-asio--asfj-as--", "-", 5); g_assert_cmpstr(split_str[0], ==, ""); g_assert_cmpstr(split_str[1], ==, ""); g_assert_cmpstr(split_str[2], ==, "aslkf"); g_assert_cmpstr(split_str[3], ==, "asio"); g_assert_cmpstr(split_str[4], ==, "-asfj-as--"); g_assert_null(split_str[5]); split_str = wmem_strsplit(allocator, "", "-", -1); g_assert_null(split_str[0]); wmem_destroy_allocator(allocator); } static void test_str_ascii(void) { wmem_allocator_t *allocator; const char *orig_str; char *new_str; allocator = wmem_allocator_new(WMEM_ALLOCATOR_BLOCK); orig_str = "TeStAsCiIsTrDoWn"; new_str = wmem_ascii_strdown(allocator, orig_str, -1); g_assert_cmpstr(new_str, ==, "testasciistrdown"); wmem_destroy_allocator(allocator); } static void test_format_text(void) { const char *have, *want; char *res; /* ASCII */ have = "abcdef"; want = "abcdef"; res = format_text_string(NULL, have); g_assert_cmpstr(res, ==, want); g_free(res); /* ASCII with special escape characters. */ have = "abc\td\fe\nf"; want = "abc\\td\\fe\\nf"; res = format_text_string(NULL, have); g_assert_cmpstr(res, ==, want); g_free(res); /* ASCII with non-printable characters. */ have = "abc \004 def"; want = "abc \\004 def"; res = format_text_string(NULL, have); g_assert_cmpstr(res, ==, want); g_free(res); /* UTF-8 */ have = u8"Γαζέες καὶ μυρτιὲς δὲν θὰ βρῶ πιὰ στὸ χρυσαφὶ ξέφωτο"; want = u8"Γαζέες καὶ μυρτιὲς δὲν θὰ βρῶ πιὰ στὸ χρυσαφὶ ξέφωτο"; res = format_text_string(NULL, have); g_assert_cmpstr(res, ==, want); g_free(res); /* UTF-8 with non-ASCII non-printable characters. */ have = u8"String with BOM \ufeff"; want = u8"String with BOM \\uFEFF"; res = format_text_string(NULL, have); g_assert_cmpstr(res, ==, want); g_free(res); } #define RESOURCE_USAGE_START get_resource_usage(&start_utime, &start_stime) #define RESOURCE_USAGE_END \ get_resource_usage(&end_utime, &end_stime); \ utime_ms = (end_utime - start_utime) * 1000.0; \ stime_ms = (end_stime - start_stime) * 1000.0 static void test_format_text_perf(void) { #define LOOP_COUNT (1 * 1000 * 1000) char *str; int i; double start_utime, start_stime, end_utime, end_stime, utime_ms, stime_ms; const char *text = "The quick brown fox\tjumps over the lazy \001dog"UTF8_HORIZONTAL_ELLIPSIS"\n"; RESOURCE_USAGE_START; for (i = 0; i < LOOP_COUNT; i++) { str = format_text_string(NULL, text); g_free(str); } RESOURCE_USAGE_END; g_test_minimized_result(utime_ms + stime_ms, "format_text_string(): u %.3f ms s %.3f ms", utime_ms, stime_ms); } #include "to_str.h" static void test_word_to_hex(void) { static char buf[32]; char *str; /* String is not NULL terminated. */ str = guint8_to_hex(buf, 0x34); g_assert_true(str == buf + 2); g_assert_cmpint(str[-1], ==, '4'); g_assert_cmpint(str[-2], ==, '3'); str = word_to_hex(buf, 0x1234); g_assert_true(str == buf + 4); g_assert_cmpint(str[-1], ==, '4'); g_assert_cmpint(str[-2], ==, '3'); g_assert_cmpint(str[-3], ==, '2'); g_assert_cmpint(str[-4], ==, '1'); str = dword_to_hex(buf, 0x1234); g_assert_true(str == buf + 8); g_assert_cmpint(str[-1], ==, '4'); g_assert_cmpint(str[-2], ==, '3'); g_assert_cmpint(str[-3], ==, '2'); g_assert_cmpint(str[-4], ==, '1'); g_assert_cmpint(str[-5], ==, '0'); g_assert_cmpint(str[-6], ==, '0'); g_assert_cmpint(str[-7], ==, '0'); g_assert_cmpint(str[-8], ==, '0'); str = qword_to_hex(buf, G_GUINT64_CONSTANT(0xFEDCBA987654321)); g_assert_true(str == buf + 16); g_assert_cmpint(str[-1], ==, '1'); g_assert_cmpint(str[-2], ==, '2'); g_assert_cmpint(str[-3], ==, '3'); g_assert_cmpint(str[-4], ==, '4'); g_assert_cmpint(str[-5], ==, '5'); g_assert_cmpint(str[-6], ==, '6'); g_assert_cmpint(str[-7], ==, '7'); g_assert_cmpint(str[-8], ==, '8'); g_assert_cmpint(str[-9], ==, '9'); g_assert_cmpint(str[-10], ==, 'a'); g_assert_cmpint(str[-11], ==, 'b'); g_assert_cmpint(str[-12], ==, 'c'); g_assert_cmpint(str[-13], ==, 'd'); g_assert_cmpint(str[-14], ==, 'e'); g_assert_cmpint(str[-15], ==, 'f'); g_assert_cmpint(str[-16], ==, '0'); } static void test_bytes_to_str(void) { char *str; const guint8 buf[] = { 1, 2, 3}; str = bytes_to_str(NULL, buf, sizeof(buf)); g_assert_cmpstr(str, ==, "010203"); g_free(str); } static void test_bytes_to_str_punct(void) { char *str; const guint8 buf[] = { 1, 2, 3}; str = bytes_to_str_punct(NULL, buf, sizeof(buf), ':'); g_assert_cmpstr(str, ==, "01:02:03"); g_free(str); } static void test_bytes_to_str_punct_maxlen(void) { char *str; const guint8 buf[] = { 1, 2, 3}; str = bytes_to_str_punct_maxlen(NULL, buf, sizeof(buf), ':', 4); g_assert_cmpstr(str, ==, "01:02:03"); g_free(str); str = bytes_to_str_punct_maxlen(NULL, buf, sizeof(buf), ':', 3); g_assert_cmpstr(str, ==, "01:02:03"); g_free(str); str = bytes_to_str_punct_maxlen(NULL, buf, sizeof(buf), ':', 2); g_assert_cmpstr(str, ==, "01:02:" UTF8_HORIZONTAL_ELLIPSIS); g_free(str); str = bytes_to_str_punct_maxlen(NULL, buf, sizeof(buf), ':', 1); g_assert_cmpstr(str, ==, "01:" UTF8_HORIZONTAL_ELLIPSIS); g_free(str); str = bytes_to_str_punct_maxlen(NULL, buf, sizeof(buf), ':', 0); g_assert_cmpstr(str, ==, "01:02:03"); g_free(str); } static void test_bytes_to_str_maxlen(void) { char *str; const guint8 buf[] = { 1, 2, 3}; str = bytes_to_str_maxlen(NULL, buf, sizeof(buf), 4); g_assert_cmpstr(str, ==, "010203"); g_free(str); str = bytes_to_str_maxlen(NULL, buf, sizeof(buf), 3); g_assert_cmpstr(str, ==, "010203"); g_free(str); str = bytes_to_str_maxlen(NULL, buf, sizeof(buf), 2); g_assert_cmpstr(str, ==, "0102" UTF8_HORIZONTAL_ELLIPSIS); g_free(str); str = bytes_to_str_maxlen(NULL, buf, sizeof(buf), 1); g_assert_cmpstr(str, ==, "01" UTF8_HORIZONTAL_ELLIPSIS); g_free(str); str = bytes_to_str_maxlen(NULL, buf, sizeof(buf), 0); g_assert_cmpstr(str, ==, "010203"); g_free(str); } static void test_bytes_to_string_trunc1(void) { char *str; const guint8 buf[] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }; const char *expect = "112233445566778899aa" "112233445566778899aa" "112233445566778899aa" "112233445566" UTF8_HORIZONTAL_ELLIPSIS; str = bytes_to_str(NULL, buf, sizeof(buf)); g_assert_cmpstr(str, ==, expect); g_free(str); } static void test_bytes_to_string_punct_trunc1(void) { char *str; const guint8 buf[] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA }; const char *expect = "11:22:33:44:55:66:77:88:99:aa:" "11:22:33:44:55:66:77:88:99:aa:" "11:22:33:44:" UTF8_HORIZONTAL_ELLIPSIS; str = bytes_to_str_punct(NULL, buf, sizeof(buf), ':'); g_assert_cmpstr(str, ==, expect); g_free(str); } static char to_str_back_buf[32]; #define BACK_PTR (&to_str_back_buf[31]) /* pointer to NUL string terminator */ static void test_oct_to_str_back(void) { char *str; str = oct_to_str_back(BACK_PTR, 958769886); g_assert_cmpstr(str, ==, "07111325336"); str = oct_to_str_back(BACK_PTR, 781499127); g_assert_cmpstr(str, ==, "05645135367"); str = oct_to_str_back(BACK_PTR, 1177329882); g_assert_cmpstr(str, ==, "010613120332"); } static void test_oct64_to_str_back(void) { char *str; str = oct64_to_str_back(BACK_PTR, G_GUINT64_CONSTANT(13873797580070999420)); g_assert_cmpstr(str, ==, "01402115026217563452574"); str = oct64_to_str_back(BACK_PTR, G_GUINT64_CONSTANT(7072159458371400691)); g_assert_cmpstr(str, ==, "0610452670726711271763"); str = oct64_to_str_back(BACK_PTR, G_GUINT64_CONSTANT(12453513102400590374)); g_assert_cmpstr(str, ==, "01263236102754220511046"); } static void test_hex_to_str_back_len(void) { char *str; str = hex_to_str_back_len(BACK_PTR, 2481, 8); g_assert_cmpstr(str, ==, "0x000009b1"); str = hex_to_str_back_len(BACK_PTR, 2457, 8); g_assert_cmpstr(str, ==, "0x00000999"); str = hex_to_str_back_len(BACK_PTR, 16230, 8); g_assert_cmpstr(str, ==, "0x00003f66"); } static void test_hex64_to_str_back_len(void) { char *str; str = hex64_to_str_back_len(BACK_PTR, G_GUINT64_CONSTANT(1), 16); g_assert_cmpstr(str, ==, "0x0000000000000001"); str = hex64_to_str_back_len(BACK_PTR, G_GUINT64_CONSTANT(4294967295), 16); g_assert_cmpstr(str, ==, "0x00000000ffffffff"); str = hex64_to_str_back_len(BACK_PTR, G_GUINT64_CONSTANT(18446744073709551615), 16); g_assert_cmpstr(str, ==, "0xffffffffffffffff"); } static void test_uint_to_str_back(void) { char *str; str = uint_to_str_back(BACK_PTR, 873735883); g_assert_cmpstr(str, ==, "873735883"); str = uint_to_str_back(BACK_PTR, 1801148094); g_assert_cmpstr(str, ==, "1801148094"); str = uint_to_str_back(BACK_PTR, 181787997); g_assert_cmpstr(str, ==, "181787997"); } static void test_uint64_to_str_back(void) { char *str; str = uint64_to_str_back(BACK_PTR, G_GUINT64_CONSTANT(585143757104211265)); g_assert_cmpstr(str, ==, "585143757104211265"); str = uint64_to_str_back(BACK_PTR, G_GUINT64_CONSTANT(7191580247919484847)); g_assert_cmpstr(str, ==, "7191580247919484847"); str = uint64_to_str_back(BACK_PTR, G_GUINT64_CONSTANT(95778573911934485)); g_assert_cmpstr(str, ==, "95778573911934485"); } static void test_uint_to_str_back_len(void) { char *str; str = uint_to_str_back_len(BACK_PTR, 26630, 8); g_assert_cmpstr(str, ==, "00026630"); str = uint_to_str_back_len(BACK_PTR, 25313, 8); g_assert_cmpstr(str, ==, "00025313"); str = uint_to_str_back_len(BACK_PTR, 18750000, 8); g_assert_cmpstr(str, ==, "18750000"); } static void test_uint64_to_str_back_len(void) { char *str; str = uint64_to_str_back_len(BACK_PTR, G_GUINT64_CONSTANT(1), 16); g_assert_cmpstr(str, ==, "0000000000000001"); str = uint64_to_str_back_len(BACK_PTR, G_GUINT64_CONSTANT(4294967295), 16); g_assert_cmpstr(str, ==, "0000004294967295"); str = uint64_to_str_back_len(BACK_PTR, G_GUINT64_CONSTANT(18446744073709551615), 16); g_assert_cmpstr(str, ==, "18446744073709551615"); } static void test_int_to_str_back(void) { char *str; str = int_to_str_back(BACK_PTR, -763689611); g_assert_cmpstr(str, ==, "-763689611"); str = int_to_str_back(BACK_PTR, -296015954); g_assert_cmpstr(str, ==, "-296015954"); str = int_to_str_back(BACK_PTR, 898901469); g_assert_cmpstr(str, ==, "898901469"); } static void test_int64_to_str_back(void) { char *str; str = int64_to_str_back(BACK_PTR, G_GINT64_CONSTANT(-9223372036854775807)); g_assert_cmpstr(str, ==, "-9223372036854775807"); str = int64_to_str_back(BACK_PTR, G_GINT64_CONSTANT(1)); g_assert_cmpstr(str, ==, "1"); str = int64_to_str_back(BACK_PTR, G_GINT64_CONSTANT(9223372036854775807)); g_assert_cmpstr(str, ==, "9223372036854775807"); } #include "nstime.h" #include "time_util.h" void test_nstime_from_iso8601(void) { char *str; size_t chars; nstime_t result, expect; struct tm tm1; memset(&tm1, 0, sizeof(tm1)); tm1.tm_sec = 25; tm1.tm_min = 45; tm1.tm_hour = 23; tm1.tm_mday = 30; tm1.tm_mon = 4; /* starts at zero */ tm1.tm_year = 2013 - 1900; tm1.tm_isdst = -1; /* Date and time with local time. */ str = "2013-05-30T23:45:25.349124"; expect.secs = mktime(&tm1); expect.nsecs = 349124 * 1000; chars = iso8601_to_nstime(&result, str, ISO8601_DATETIME_AUTO); g_assert_cmpuint(chars, ==, strlen(str)); g_assert_cmpint(result.secs, ==, expect.secs); g_assert_cmpint(result.nsecs, ==, expect.nsecs); /* Date and time with UTC timezone. */ str = "2013-05-30T23:45:25.349124Z"; expect.secs = mktime_utc(&tm1); expect.nsecs = 349124 * 1000; chars = iso8601_to_nstime(&result, str, ISO8601_DATETIME_AUTO); g_assert_cmpuint(chars, ==, strlen(str)); g_assert_cmpint(result.secs, ==, expect.secs); g_assert_cmpint(result.nsecs, ==, expect.nsecs); /* Date and time with timezone offset with separator. */ str = "2013-05-30T23:45:25.349124+01:00"; expect.secs = mktime_utc(&tm1) - 1 * 60 * 60; expect.nsecs = 349124 * 1000; chars = iso8601_to_nstime(&result, str, ISO8601_DATETIME_AUTO); g_assert_cmpuint(chars, ==, strlen(str)); g_assert_cmpint(result.secs, ==, expect.secs); g_assert_cmpint(result.nsecs, ==, expect.nsecs); /* Date and time with timezone offset without separator. */ str = "2013-05-30T23:45:25.349124+0100"; expect.secs = mktime_utc(&tm1) - 1 * 60 * 60; expect.nsecs = 349124 * 1000; chars = iso8601_to_nstime(&result, str, ISO8601_DATETIME_AUTO); g_assert_cmpuint(chars, ==, strlen(str)); g_assert_cmpint(result.secs, ==, expect.secs); g_assert_cmpint(result.nsecs, ==, expect.nsecs); /* Date and time with timezone offset with hours only. */ str = "2013-05-30T23:45:25.349124+01"; expect.secs = mktime_utc(&tm1) - 1 * 60 * 60; expect.nsecs = 349124 * 1000; chars = iso8601_to_nstime(&result, str, ISO8601_DATETIME_AUTO); g_assert_cmpuint(chars, ==, strlen(str)); g_assert_cmpint(result.secs, ==, expect.secs); g_assert_cmpint(result.nsecs, ==, expect.nsecs); } #include "ws_getopt.h" #define ARGV_MAX 31 static char **new_argv(int *argc_ptr, const char *args, ...) { char **argv; int argc = 0; va_list ap; argv = g_malloc((ARGV_MAX + 1) * sizeof(char *)); va_start(ap, args); while (args != NULL) { /* Increase ARGV_MAX or use a dynamic size if this assertion fails. */ g_assert_true(argc < ARGV_MAX); argv[argc++] = g_strdup(args); args = va_arg(ap, const char *); } argv[argc] = NULL; va_end(ap); *argc_ptr = argc; return argv; } static void free_argv(char **argv) { for (char **p = argv; *p != NULL; p++) { g_free(*p); } g_free(argv); } static void test_getopt_long_basic1(void) { char **argv; int argc; const char *optstring = "ab:c"; argv = new_argv(&argc, "/bin/ls", "-a", "-b", "arg1", "-c", "path", (char *)NULL); ws_optind = 1; int opt; opt = ws_getopt_long(argc, argv, optstring, NULL, NULL); g_assert_cmpint(opt, ==, 'a'); g_assert_null(ws_optarg); opt = ws_getopt_long(argc, argv, optstring, NULL, NULL); g_assert_cmpint(opt, ==, 'b'); g_assert_cmpstr(ws_optarg, ==, "arg1"); opt = ws_getopt_long(argc, argv, optstring, NULL, NULL); g_assert_cmpint(opt, ==, 'c'); g_assert_null(ws_optarg); opt = ws_getopt_long(argc, argv, optstring, NULL, NULL); g_assert_cmpint(opt, ==, -1); free_argv(argv); } static void test_getopt_long_basic2(void) { char **argv; int argc; struct ws_option longopts[] = { { "opt1", ws_no_argument, NULL, '1' }, { "opt2", ws_required_argument, NULL, '2' }, { "opt3", ws_required_argument, NULL, '3' }, { 0, 0, 0, 0 } }; argv = new_argv(&argc, "/bin/ls", "--opt1", "--opt2", "arg1", "--opt3=arg2", "path", (char *)NULL); ws_optind = 1; int opt; opt = ws_getopt_long(argc, argv, "", longopts, NULL); g_assert_cmpint(opt, ==, '1'); g_assert_null(ws_optarg); opt = ws_getopt_long(argc, argv, "", longopts, NULL); g_assert_cmpint(opt, ==, '2'); g_assert_cmpstr(ws_optarg, ==, "arg1"); opt = ws_getopt_long(argc, argv, "", longopts, NULL); g_assert_cmpint(opt, ==, '3'); g_assert_cmpstr(ws_optarg, ==, "arg2"); opt = ws_getopt_long(argc, argv, "", longopts, NULL); g_assert_cmpint(opt, ==, -1); free_argv(argv); } static void test_getopt_optional_argument1(void) { char **argv; int argc; int opt; struct ws_option longopts_optional[] = { { "optional", ws_optional_argument, NULL, '1' }, { 0, 0, 0, 0 } }; argv = new_argv(&argc, "/bin/ls", "--optional=arg1", (char *)NULL); ws_optreset = 1; opt = ws_getopt_long(argc, argv, "", longopts_optional, NULL); g_assert_cmpint(opt, ==, '1'); g_assert_cmpstr(ws_optarg, ==, "arg1"); free_argv(argv); argv = new_argv(&argc, "/bin/ls", "--optional", "arg1", (char *)NULL); ws_optreset = 1; opt = ws_getopt_long(argc, argv, "", longopts_optional, NULL); g_assert_cmpint(opt, ==, '1'); /* Optional argument does not recognize the form "--arg param" (it's ambiguous). */ g_assert_null(ws_optarg); free_argv(argv); argv = new_argv(&argc, "/bin/ls", "--optional", (char *)NULL); ws_optreset = 1; opt = ws_getopt_long(argc, argv, "", longopts_optional, NULL); g_assert_cmpint(opt, ==, '1'); g_assert_null(ws_optarg); free_argv(argv); } static void test_getopt_opterr1(void) { char **argv; int argc; #ifdef _WIN32 g_test_skip("Not supported on Windows"); return; #endif if (g_test_subprocess()) { const char *optstring = "ab"; argv = new_argv(&argc, "/bin/ls", "-a", "-z", "path", (char *)NULL); ws_optind = 0; ws_opterr = 1; int opt; opt = ws_getopt_long(argc, argv, optstring, NULL, NULL); g_assert_cmpint(opt, ==, 'a'); opt = ws_getopt_long(argc, argv, optstring, NULL, NULL); g_assert_cmpint(opt, ==, '?'); g_assert_cmpint(ws_optopt, ==, 'z'); opt = ws_getopt_long(argc, argv, optstring, NULL, NULL); g_assert_cmpint(opt, ==, -1); free_argv(argv); return; } g_test_trap_subprocess(NULL, 0, 0); g_test_trap_assert_passed(); g_test_trap_assert_stderr("/bin/ls: unrecognized option: z\n"); } int main(int argc, char **argv) { int ret; ws_log_init("test_wsutil", NULL); g_test_init(&argc, &argv, NULL); g_test_add_func("/inet_addr/inet_pton4", test_inet_pton4_test1); g_test_add_func("/inet_addr/inet_ntop4", test_inet_ntop4_test1); g_test_add_func("/inet_addr/inet_pton6", test_inet_pton6_test1); g_test_add_func("/inet_addr/inet_ntop6", test_inet_ntop6_test1); g_test_add_func("/str_util/format_size", test_format_size); g_test_add_func("/str_util/escape_string", test_escape_string); g_test_add_func("/str_util/strconcat", test_strconcat); g_test_add_func("/str_util/strsplit", test_strsplit); g_test_add_func("/str_util/str_ascii", test_str_ascii); g_test_add_func("/str_util/format_text", test_format_text); if (g_test_perf()) { g_test_add_func("/str_util/format_text_perf", test_format_text_perf); } g_test_add_func("/to_str/word_to_hex", test_word_to_hex); g_test_add_func("/to_str/bytes_to_str", test_bytes_to_str); g_test_add_func("/to_str/bytes_to_str_punct", test_bytes_to_str_punct); g_test_add_func("/to_str/bytes_to_str_maxlen", test_bytes_to_str_maxlen); g_test_add_func("/to_str/bytes_to_str_punct_maxlen", test_bytes_to_str_punct_maxlen); g_test_add_func("/to_str/bytes_to_str_trunc1", test_bytes_to_string_trunc1); g_test_add_func("/to_str/bytes_to_str_punct_trunc1", test_bytes_to_string_punct_trunc1); g_test_add_func("/to_str/oct_to_str_back", test_oct_to_str_back); g_test_add_func("/to_str/oct64_to_str_back", test_oct64_to_str_back); g_test_add_func("/to_str/hex_to_str_back_len", test_hex_to_str_back_len); g_test_add_func("/to_str/hex64_to_str_back_len", test_hex64_to_str_back_len); g_test_add_func("/to_str/uint_to_str_back", test_uint_to_str_back); g_test_add_func("/to_str/uint64_to_str_back", test_uint64_to_str_back); g_test_add_func("/to_str/uint_to_str_back_len", test_uint_to_str_back_len); g_test_add_func("/to_str/uint64_to_str_back_len", test_uint64_to_str_back_len); g_test_add_func("/to_str/int_to_str_back", test_int_to_str_back); g_test_add_func("/to_str/int64_to_str_back", test_int64_to_str_back); g_test_add_func("/nstime/from_iso8601", test_nstime_from_iso8601); g_test_add_func("/ws_getopt/basic1", test_getopt_long_basic1); g_test_add_func("/ws_getopt/basic2", test_getopt_long_basic2); g_test_add_func("/ws_getopt/optional1", test_getopt_optional_argument1); g_test_add_func("/ws_getopt/opterr1", test_getopt_opterr1); ret = g_test_run(); return ret; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C
wireshark/wsutil/time_util.c
/* time_util.c * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #define _GNU_SOURCE /* For strptime(). */ #include "config.h" #define WS_LOG_DOMAIN LOG_DOMAIN_WSUTIL #include "time_util.h" #include <wsutil/epochs.h> #ifndef _WIN32 #include <sys/time.h> #include <sys/resource.h> #else #include <windows.h> #endif #ifndef HAVE_STRPTIME #include "strptime.h" #endif /* Test if the given year is a leap year */ #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) /* converts a broken down date representation, relative to UTC, * to a timestamp; it uses timegm() if it's available. * Copied from Glib source gtimer.c */ time_t mktime_utc(struct tm *tm) { #ifndef HAVE_TIMEGM time_t retval; static const int days_before[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; int yr; if (tm->tm_mon < 0 || tm->tm_mon > 11) return (time_t) -1; retval = (tm->tm_year - 70) * 365; /* count number of leap years */ yr = tm->tm_year + 1900; if (tm->tm_mon + 1 < 3 && isleap(yr)) yr--; retval += (((yr / 4) - (yr / 100) + (yr / 400)) - 477); /* 477 = ((1970 / 4) - (1970 / 100) + (1970 / 400)) */ retval += days_before[tm->tm_mon] + tm->tm_mday - 1; retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec; return retval; #else return timegm(tm); #endif /* !HAVE_TIMEGM */ } /* Validate the values in a time_t * Currently checks tm_year, tm_mon, tm_mday, tm_hour, tm_min, and tm_sec; * disregards tm_wday, tm_yday, and tm_isdst. * Use this in situations where you wish to return an error rather than * normalizing invalid dates; otherwise you could specify, for example, * 2020-10-40 (to quote the macOS and probably *BSD manual * page for ctime()/localtime()/mktime()/etc., "October 40 * is changed into November 9"). */ gboolean tm_is_valid(struct tm *tm) { static const gint8 days_in_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (tm->tm_mon < 0 || tm->tm_mon > 11) { return FALSE; } if (tm->tm_mday < 0 || tm->tm_mday > ((tm->tm_mon == 1 && isleap(tm->tm_year)) ? 29 : days_in_month[tm->tm_mon])) { return FALSE; } if (tm->tm_hour < 0 || tm->tm_hour > 23) { return FALSE; } /* XXX: ISO 8601 and others allow 24:00:00 for end of day, perhaps that * one case should be allowed? */ if (tm->tm_min < 0 || tm->tm_min > 59) { return FALSE; } if (tm->tm_sec < 0 || tm->tm_sec > 60) { /* 60, not 59, to account for leap seconds */ return FALSE; } return TRUE; } void get_resource_usage(double *user_time, double *sys_time) { #ifndef _WIN32 struct rusage ru; getrusage(RUSAGE_SELF, &ru); *user_time = ru.ru_utime.tv_sec + (ru.ru_utime.tv_usec / 1000000.0); *sys_time = ru.ru_stime.tv_sec + (ru.ru_stime.tv_usec / 1000000.0); #else /* _WIN32 */ HANDLE h_proc = GetCurrentProcess(); FILETIME cft, eft, kft, uft; ULARGE_INTEGER uli_time; GetProcessTimes(h_proc, &cft, &eft, &kft, &uft); uli_time.LowPart = uft.dwLowDateTime; uli_time.HighPart = uft.dwHighDateTime; *user_time = uli_time.QuadPart / 10000000.0; uli_time.LowPart = kft.dwLowDateTime; uli_time.HighPart = kft.dwHighDateTime; *sys_time = uli_time.QuadPart / 1000000000.0; #endif /* _WIN32 */ } static double last_user_time = 0.0; static double last_sys_time = 0.0; void log_resource_usage(gboolean reset_delta, const char *format, ...) { va_list ap; GString *log_str = g_string_new(""); double user_time; double sys_time; get_resource_usage(&user_time, &sys_time); if (reset_delta || last_user_time == 0.0) { last_user_time = user_time; last_sys_time = sys_time; } g_string_append_printf(log_str, "user %.3f +%.3f sys %.3f +%.3f ", user_time, user_time - last_user_time, sys_time, sys_time - last_sys_time); va_start(ap, format); g_string_append_vprintf(log_str, format, ap); va_end(ap); ws_warning("%s", log_str->str); g_string_free(log_str, TRUE); } /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/ guint64 create_timestamp(void) { guint64 timestamp; #ifdef _WIN32 FILETIME now; #else struct timeval now; #endif #ifdef _WIN32 /* * Current time, represented as 100-nanosecond intervals since * January 1, 1601, 00:00:00 UTC. * * I think DWORD might be signed, so cast both parts of "now" * to guint32 so that the sign bit doesn't get treated specially. * * Windows 8 provides GetSystemTimePreciseAsFileTime which we * might want to use instead. */ GetSystemTimeAsFileTime(&now); timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) + (guint32)now.dwLowDateTime; /* * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond, * intervals. */ timestamp /= 10; /* * Subtract difference, in microseconds, between January 1, 1601 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC. */ timestamp -= EPOCH_DELTA_1601_01_01_00_00_00_UTC*1000000; #else /* * Current time, represented as seconds and microseconds since * January 1, 1970, 00:00:00 UTC. */ gettimeofday(&now, NULL); /* * Convert to delta in microseconds. */ timestamp = (guint64)(now.tv_sec) * 1000000 + (guint64)(now.tv_usec); #endif return timestamp; } struct timespec * ws_clock_get_realtime(struct timespec *ts) { /* * This function is used in the wslog log handler context. * We must not call anything, even indirectly, that might log a message * using wslog (including GLib). */ #if defined(HAVE_CLOCK_GETTIME) if (clock_gettime(CLOCK_REALTIME, ts) == 0) return ts; #elif defined(HAVE_TIMESPEC_GET) if (timespec_get(ts, TIME_UTC) == TIME_UTC) return ts; #endif #ifndef _WIN32 /* Fall back on gettimeofday(). */ struct timeval usectimenow; gettimeofday(&usectimenow, NULL); ts->tv_sec = usectimenow.tv_sec; ts->tv_nsec = usectimenow.tv_usec*1000; return ts; #else /* Fall back on time(). */ ts->tv_sec = time(NULL); ts->tv_nsec = 0; return ts; #endif } char *ws_strptime(const char *restrict s, const char *restrict format, struct tm *restrict tm) { #ifdef HAVE_STRPTIME return strptime(s, format, tm); #else return strptime_gnulib(s, format, tm); #endif } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/time_util.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __TIME_UTIL_H__ #define __TIME_UTIL_H__ #include <wireshark.h> #include <time.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** Converts a broken down date representation, relative to UTC, * to a timestamp */ WS_DLL_PUBLIC time_t mktime_utc(struct tm *tm); /** Validate the values in a time_t. * Currently checks tm_year, tm_mon, tm_mday, tm_hour, tm_min, and tm_sec; * disregards tm_wday, tm_yday, and tm_isdst. * * @param tm The struct tm to validate. */ WS_DLL_PUBLIC gboolean tm_is_valid(struct tm *tm); /** Fetch the process CPU time. * * Fetch the current process user and system CPU times, convert them to * seconds, and store them in the provided parameters. * * @param user_time Seconds spent in user mode. * @param sys_time Seconds spent in system (kernel) mode. */ WS_DLL_PUBLIC void get_resource_usage(double *user_time, double *sys_time); /** Print the process CPU time followed by a log message. * * Print the current process user and system CPU times along with the times * elapsed since the times were last reset. * * @param reset_delta Reset the delta times. This will typically be TRUE when * logging the first measurement and FALSE thereafter. * @param format Printf-style format string. Passed to g_string_vprintf. * @param ... Parameters for the format string. */ WS_DLL_PUBLIC void log_resource_usage(gboolean reset_delta, const char *format, ...); /** * Fetch the number of microseconds since midnight (0 hour), January 1, 1970. */ WS_DLL_PUBLIC guint64 create_timestamp(void); WS_DLL_PUBLIC struct timespec *ws_clock_get_realtime(struct timespec *ts); /* * Portability wrapper around strptime(). */ WS_DLL_PUBLIC char *ws_strptime(const char *s, const char *format, struct tm *tm); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __TIME_UTIL_H__ */
C
wireshark/wsutil/to_str.c
/* wsutil/to_str.c * Routines for utilities to convert various other types to strings. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "to_str.h" #include <stdio.h> #include <string.h> #include <time.h> #include <wsutil/utf8_entities.h> #include <wsutil/wslog.h> #include <wsutil/inet_addr.h> #include <wsutil/pint.h> #include <wsutil/ws_return.h> /* * If a user _does_ pass in a too-small buffer, this is probably * going to be too long to fit. However, even a partial string * starting with "[Buf" should provide enough of a clue to be * useful. */ #define _return_if_nospace(str_len, buf, buf_len) \ do { \ if ((str_len) > (buf_len)) { \ (void)g_strlcpy(buf, "[Buffer too small]", buf_len); \ return; \ } \ } while (0) static const char fast_strings[][4] = { "0", "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" }; static inline char low_nibble_of_octet_to_hex(guint8 oct) { /* At least one version of Apple's C compiler/linker is buggy, causing a complaint from the linker about the "literal C string section" not ending with '\0' if we initialize a 16-element "char" array with a 16-character string, the fact that initializing such an array with such a string is perfectly legitimate ANSI C nonwithstanding, the 17th '\0' byte in the string nonwithstanding. */ static const gchar hex_digits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; return hex_digits[oct & 0xF]; } static inline char * byte_to_hex(char *out, guint32 dword) { *out++ = low_nibble_of_octet_to_hex(dword >> 4); *out++ = low_nibble_of_octet_to_hex(dword); return out; } char * guint8_to_hex(char *out, guint8 val) { return byte_to_hex(out, val); } char * word_to_hex(char *out, guint16 word) { out = byte_to_hex(out, word >> 8); out = byte_to_hex(out, word); return out; } char * word_to_hex_punct(char *out, guint16 word, char punct) { out = byte_to_hex(out, word >> 8); *out++ = punct; out = byte_to_hex(out, word); return out; } char * word_to_hex_npad(char *out, guint16 word) { if (word >= 0x1000) *out++ = low_nibble_of_octet_to_hex((guint8)(word >> 12)); if (word >= 0x0100) *out++ = low_nibble_of_octet_to_hex((guint8)(word >> 8)); if (word >= 0x0010) *out++ = low_nibble_of_octet_to_hex((guint8)(word >> 4)); *out++ = low_nibble_of_octet_to_hex((guint8)(word >> 0)); return out; } char * dword_to_hex(char *out, guint32 dword) { out = word_to_hex(out, dword >> 16); out = word_to_hex(out, dword); return out; } char * dword_to_hex_punct(char *out, guint32 dword, char punct) { out = word_to_hex_punct(out, dword >> 16, punct); *out++ = punct; out = word_to_hex_punct(out, dword, punct); return out; } char * qword_to_hex(char *out, guint64 qword) { out = dword_to_hex(out, (guint32)(qword >> 32)); out = dword_to_hex(out, (guint32)(qword & 0xffffffff)); return out; } char * qword_to_hex_punct(char *out, guint64 qword, char punct) { out = dword_to_hex_punct(out, (guint32)(qword >> 32), punct); *out++ = punct; out = dword_to_hex_punct(out, (guint32)(qword & 0xffffffff), punct); return out; } /* * This does *not* null-terminate the string. It returns a pointer * to the position in the string following the last character it * puts there, so that the caller can either put the null terminator * in or can append more stuff to the buffer. * * There needs to be at least len * 2 bytes left in the buffer. */ char * bytes_to_hexstr(char *out, const guint8 *ad, size_t len) { size_t i; ws_return_val_if_null(ad, NULL); for (i = 0; i < len; i++) out = byte_to_hex(out, ad[i]); return out; } /* * This does *not* null-terminate the string. It returns a pointer * to the position in the string following the last character it * puts there, so that the caller can either put the null terminator * in or can append more stuff to the buffer. * * There needs to be at least len * 3 - 1 bytes left in the buffer. */ char * bytes_to_hexstr_punct(char *out, const guint8 *ad, size_t len, char punct) { size_t i; ws_return_val_if_null(ad, NULL); out = byte_to_hex(out, ad[0]); for (i = 1; i < len; i++) { *out++ = punct; out = byte_to_hex(out, ad[i]); } return out; } /* Routine to convert a sequence of bytes to a hex string, one byte/two hex * digits at a time, with a specified punctuation character between * the bytes. * * If punct is '\0', no punctuation is applied (and thus * the resulting string is (len-1) bytes shorter) */ char * bytes_to_str_punct_maxlen(wmem_allocator_t *scope, const guint8 *src, size_t src_size, char punct, size_t max_bytes_len) { char *buf; size_t max_char_size; char *buf_ptr; int truncated = 0; ws_return_str_if_null(scope, src); ws_return_str_if_zero(scope, src_size); if (!punct) return bytes_to_str_maxlen(scope, src, src_size, max_bytes_len); if (max_bytes_len == 0 || max_bytes_len > src_size) { max_bytes_len = src_size; } else if (max_bytes_len < src_size) { truncated = 1; } /* Include space for ellipsis and '\0'. Optional extra punct * at the end is already accounted for. */ max_char_size = max_bytes_len * 3 + strlen(UTF8_HORIZONTAL_ELLIPSIS) + 1; buf = wmem_alloc(scope, max_char_size); buf_ptr = bytes_to_hexstr_punct(buf, src, max_bytes_len, punct); if (truncated) { *buf_ptr++ = punct; buf_ptr = g_stpcpy(buf_ptr, UTF8_HORIZONTAL_ELLIPSIS); } *buf_ptr = '\0'; return buf; } char * bytes_to_str_maxlen(wmem_allocator_t *scope, const guint8 *src, size_t src_size, size_t max_bytes_len) { char *buf; size_t max_char_size; char *buf_ptr; int truncated = 0; ws_return_str_if_null(scope, src); ws_return_str_if_zero(scope, src_size); if (max_bytes_len == 0 || max_bytes_len > src_size) { max_bytes_len = src_size; } else if (max_bytes_len < src_size) { truncated = 1; } max_char_size = max_bytes_len * 2 + strlen(UTF8_HORIZONTAL_ELLIPSIS) + 1; buf = wmem_alloc(scope, max_char_size); buf_ptr = bytes_to_hexstr(buf, src, max_bytes_len); if (truncated) buf_ptr = g_stpcpy(buf_ptr, UTF8_HORIZONTAL_ELLIPSIS); *buf_ptr = '\0'; return buf; } /* * The *_to_str_back() functions measured approx. a x7.5 speed-up versus * snprintf() on my Linux system with GNU libc. */ char * oct_to_str_back(char *ptr, guint32 value) { while (value) { *(--ptr) = '0' + (value & 0x7); value >>= 3; } *(--ptr) = '0'; return ptr; } char * oct64_to_str_back(char *ptr, guint64 value) { while (value) { *(--ptr) = '0' + (value & 0x7); value >>= 3; } *(--ptr) = '0'; return ptr; } char * hex_to_str_back_len(char *ptr, guint32 value, int len) { do { *(--ptr) = low_nibble_of_octet_to_hex(value); value >>= 4; len--; } while (value); /* pad */ while (len > 0) { *(--ptr) = '0'; len--; } *(--ptr) = 'x'; *(--ptr) = '0'; return ptr; } char * hex64_to_str_back_len(char *ptr, guint64 value, int len) { do { *(--ptr) = low_nibble_of_octet_to_hex(value & 0xF); value >>= 4; len--; } while (value); /* pad */ while (len > 0) { *(--ptr) = '0'; len--; } *(--ptr) = 'x'; *(--ptr) = '0'; return ptr; } char * uint_to_str_back(char *ptr, guint32 value) { char const *p; /* special case */ if (value == 0) *(--ptr) = '0'; while (value >= 10) { p = fast_strings[100 + (value % 100)]; value /= 100; *(--ptr) = p[2]; *(--ptr) = p[1]; } if (value) *(--ptr) = (value) | '0'; return ptr; } char * uint64_to_str_back(char *ptr, guint64 value) { char const *p; /* special case */ if (value == 0) *(--ptr) = '0'; while (value >= 10) { p = fast_strings[100 + (value % 100)]; value /= 100; *(--ptr) = p[2]; *(--ptr) = p[1]; } /* value will be 0..9, so using '& 0xF' is safe, and faster than '% 10' */ if (value) *(--ptr) = (value & 0xF) | '0'; return ptr; } char * uint_to_str_back_len(char *ptr, guint32 value, int len) { char *new_ptr; new_ptr = uint_to_str_back(ptr, value); /* substract from len number of generated characters */ len -= (int)(ptr - new_ptr); /* pad remaining with '0' */ while (len > 0) { *(--new_ptr) = '0'; len--; } return new_ptr; } char * uint64_to_str_back_len(char *ptr, guint64 value, int len) { char *new_ptr; new_ptr = uint64_to_str_back(ptr, value); /* substract from len number of generated characters */ len -= (int)(ptr - new_ptr); /* pad remaining with '0' */ while (len > 0) { *(--new_ptr) = '0'; len--; } return new_ptr; } char * int_to_str_back(char *ptr, gint32 value) { if (value < 0) { ptr = uint_to_str_back(ptr, -value); *(--ptr) = '-'; } else ptr = uint_to_str_back(ptr, value); return ptr; } char * int64_to_str_back(char *ptr, gint64 value) { if (value < 0) { ptr = uint64_to_str_back(ptr, -value); *(--ptr) = '-'; } else ptr = uint64_to_str_back(ptr, value); return ptr; } static size_t guint32_to_str_buf_len(const guint32 u) { /* ((2^32)-1) == 2147483647 */ if (u >= 1000000000)return 10; if (u >= 100000000) return 9; if (u >= 10000000) return 8; if (u >= 1000000) return 7; if (u >= 100000) return 6; if (u >= 10000) return 5; if (u >= 1000) return 4; if (u >= 100) return 3; if (u >= 10) return 2; return 1; } void guint32_to_str_buf(guint32 u, gchar *buf, size_t buf_len) { size_t str_len = guint32_to_str_buf_len(u)+1; gchar *bp = &buf[str_len]; _return_if_nospace(str_len, buf, buf_len); *--bp = '\0'; uint_to_str_back(bp, u); } static size_t guint64_to_str_buf_len(const guint64 u) { /* ((2^64)-1) == 18446744073709551615 */ if (u >= G_GUINT64_CONSTANT(10000000000000000000)) return 20; if (u >= G_GUINT64_CONSTANT(1000000000000000000)) return 19; if (u >= G_GUINT64_CONSTANT(100000000000000000)) return 18; if (u >= G_GUINT64_CONSTANT(10000000000000000)) return 17; if (u >= G_GUINT64_CONSTANT(1000000000000000)) return 16; if (u >= G_GUINT64_CONSTANT(100000000000000)) return 15; if (u >= G_GUINT64_CONSTANT(10000000000000)) return 14; if (u >= G_GUINT64_CONSTANT(1000000000000)) return 13; if (u >= G_GUINT64_CONSTANT(100000000000)) return 12; if (u >= G_GUINT64_CONSTANT(10000000000)) return 11; if (u >= G_GUINT64_CONSTANT(1000000000)) return 10; if (u >= G_GUINT64_CONSTANT(100000000)) return 9; if (u >= G_GUINT64_CONSTANT(10000000)) return 8; if (u >= G_GUINT64_CONSTANT(1000000)) return 7; if (u >= G_GUINT64_CONSTANT(100000)) return 6; if (u >= G_GUINT64_CONSTANT(10000)) return 5; if (u >= G_GUINT64_CONSTANT(1000)) return 4; if (u >= G_GUINT64_CONSTANT(100)) return 3; if (u >= G_GUINT64_CONSTANT(10)) return 2; return 1; } void guint64_to_str_buf(guint64 u, gchar *buf, size_t buf_len) { size_t str_len = guint64_to_str_buf_len(u)+1; gchar *bp = &buf[str_len]; _return_if_nospace(str_len, buf, buf_len); *--bp = '\0'; uint64_to_str_back(bp, u); } /* This function is very fast and this function is called a lot. XXX update the address_to_str stuff to use this function. */ void ip_to_str_buf(const guint8 *ad, gchar *buf, const int buf_len) { register gchar const *p; register gchar *b=buf; _return_if_nospace(WS_INET_ADDRSTRLEN, buf, buf_len); p=fast_strings[*ad++]; do { *b++=*p; p++; } while(*p); *b++='.'; p=fast_strings[*ad++]; do { *b++=*p; p++; } while(*p); *b++='.'; p=fast_strings[*ad++]; do { *b++=*p; p++; } while(*p); *b++='.'; p=fast_strings[*ad]; do { *b++=*p; p++; } while(*p); *b=0; } char *ip_to_str(wmem_allocator_t *scope, const guint8 *ad) { char *buf = wmem_alloc(scope, WS_INET_ADDRSTRLEN * sizeof(char)); ip_to_str_buf(ad, buf, WS_INET_ADDRSTRLEN); return buf; } void ip6_to_str_buf(const ws_in6_addr *addr, gchar *buf, size_t buf_size) { /* * If there is not enough space then ws_inet_ntop6() will leave * an error message in the buffer, we don't need * to use _return_if_nospace(). */ ws_inet_ntop6(addr, buf, (guint)buf_size); } char *ip6_to_str(wmem_allocator_t *scope, const ws_in6_addr *ad) { char *buf = wmem_alloc(scope, WS_INET6_ADDRSTRLEN * sizeof(char)); ws_inet_ntop6(ad, buf, WS_INET6_ADDRSTRLEN); return buf; } gchar * ipxnet_to_str_punct(wmem_allocator_t *allocator, const guint32 ad, const char punct) { gchar *buf = (gchar *)wmem_alloc(allocator, 12); *dword_to_hex_punct(buf, ad, punct) = '\0'; return buf; } #define WS_EUI64_STRLEN 24 gchar * eui64_to_str(wmem_allocator_t *scope, const guint64 ad) { gchar *buf, *tmp; guint8 *p_eui64; p_eui64=(guint8 *)wmem_alloc(NULL, 8); buf=(gchar *)wmem_alloc(scope, WS_EUI64_STRLEN); /* Copy and convert the address to network byte order. */ *(guint64 *)(void *)(p_eui64) = pntoh64(&(ad)); tmp = bytes_to_hexstr_punct(buf, p_eui64, 8, ':'); *tmp = '\0'; /* NULL terminate */ wmem_free(NULL, p_eui64); return buf; } void display_epoch_time(gchar *buf, size_t buflen, const time_t sec, gint32 frac, const ws_tsprec_e units) { double elapsed_secs; elapsed_secs = difftime(sec,(time_t)0); /* This code copied from display_signed_time; keep it in case anyone is looking at captures from before 1970 (???). If the fractional part of the time stamp is negative, print its absolute value and, if the seconds part isn't (the seconds part should be zero in that case), stick a "-" in front of the entire time stamp. */ if (frac < 0) { frac = -frac; if (elapsed_secs >= 0) { if (buflen < 1) { return; } buf[0] = '-'; buf++; buflen--; } } switch (units) { case WS_TSPREC_SEC: snprintf(buf, buflen, "%0.0f", elapsed_secs); break; case WS_TSPREC_100_MSEC: snprintf(buf, buflen, "%0.0f.%01d", elapsed_secs, frac); break; case WS_TSPREC_10_MSEC: snprintf(buf, buflen, "%0.0f.%02d", elapsed_secs, frac); break; case WS_TSPREC_MSEC: snprintf(buf, buflen, "%0.0f.%03d", elapsed_secs, frac); break; case WS_TSPREC_USEC: snprintf(buf, buflen, "%0.0f.%06d", elapsed_secs, frac); break; case WS_TSPREC_NSEC: snprintf(buf, buflen, "%0.0f.%09d", elapsed_secs, frac); break; } } /* * Number of characters required by a 64-bit signed number. */ #define CHARS_64_BIT_SIGNED 20 /* sign plus 19 digits */ /* * Number of characters required by a fractional part, in nanoseconds */ #define CHARS_NANOSECONDS 10 /* .000000001 */ void display_signed_time(gchar *buf, size_t buflen, const gint64 sec, gint32 frac, const ws_tsprec_e units) { /* this buffer is not NUL terminated */ gint8 num_buf[CHARS_64_BIT_SIGNED]; gint8 *num_end = &num_buf[CHARS_64_BIT_SIGNED]; gint8 *num_ptr; size_t num_len; if (buflen < 1) return; /* If the fractional part of the time stamp is negative, print its absolute value and, if the seconds part isn't (the seconds part should be zero in that case), stick a "-" in front of the entire time stamp. */ if (frac < 0) { frac = -frac; if (sec >= 0) { buf[0] = '-'; buf++; buflen--; } } num_ptr = int64_to_str_back(num_end, sec); num_len = MIN((size_t)(num_end - num_ptr), buflen); memcpy(buf, num_ptr, num_len); buf += num_len; buflen -= num_len; switch (units) { case WS_TSPREC_SEC: default: /* no fraction */ num_ptr = NULL; break; case WS_TSPREC_100_MSEC: num_ptr = uint_to_str_back_len(num_end, frac, 1); break; case WS_TSPREC_10_MSEC: num_ptr = uint_to_str_back_len(num_end, frac, 2); break; case WS_TSPREC_MSEC: num_ptr = uint_to_str_back_len(num_end, frac, 3); break; case WS_TSPREC_USEC: num_ptr = uint_to_str_back_len(num_end, frac, 6); break; case WS_TSPREC_NSEC: num_ptr = uint_to_str_back_len(num_end, frac, 9); break; } if (num_ptr != NULL) { *(--num_ptr) = '.'; num_len = MIN((size_t)(num_end - num_ptr), buflen); memcpy(buf, num_ptr, num_len); buf += num_len; buflen -= num_len; } /* need to NUL terminate, we know that buffer had at least 1 byte */ if (buflen == 0) buf--; *buf = '\0'; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/to_str.h
/** @file * * Definitions for utilities to convert various other types to strings. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WSUTIL_TO_STR_H__ #define __WSUTIL_TO_STR_H__ #include <wireshark.h> #include <wsutil/wmem/wmem.h> #include <wsutil/inet_ipv6.h> #include <wsutil/nstime.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * guint8_to_hex() * * Output guint8 hex representation to 'out', and return pointer after last character (out + 2). * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least 2 bytes in the buffer. */ WS_DLL_PUBLIC char *guint8_to_hex(char *out, guint8 val); /** * word_to_hex() * * Output guint16 hex representation to 'out', and return pointer after last character (out + 4). * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least 4 bytes in the buffer. */ WS_DLL_PUBLIC char *word_to_hex(char *out, guint16 word); /** * word_to_hex_punct() * * Output guint16 hex representation to 'out', and return pointer after last character. * Each byte will be separated with punct character (cannot be NUL). * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least 5 bytes in the buffer. */ WS_DLL_PUBLIC char *word_to_hex_punct(char *out, guint16 word, char punct); /** * word_to_hex_npad() * * Output guint16 hex representation to 'out', and return pointer after last character. * Value is not padded. * * String is not NUL terminated by this routine. * There needs to be at least 4 bytes in the buffer. */ WS_DLL_PUBLIC char *word_to_hex_npad(char *out, guint16 word); /** * dword_to_hex() * * Output guint32 hex representation to 'out', and return pointer after last character. * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least 8 bytes in the buffer. */ WS_DLL_PUBLIC char *dword_to_hex(char *out, guint32 dword); /** * dword_to_hex_punct() * * Output guint32 hex representation to 'out', and return pointer after last character. * Each byte will be separated with punct character (cannot be NUL). * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least 11 bytes in the buffer. */ WS_DLL_PUBLIC char *dword_to_hex_punct(char *out, guint32 dword, char punct); /** * qword_to_hex() * * Output guint64 hex representation to 'out', and return pointer after last character. * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least 16 bytes in the buffer. */ WS_DLL_PUBLIC char *qword_to_hex(char *out, guint64 qword); /** * qword_to_hex_punct() * * Output guint64 hex representation to 'out', and return pointer after last character. * Each byte will be separated with punct character (cannot be NUL). * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least 22 bytes in the buffer. */ WS_DLL_PUBLIC char *qword_to_hex_punct(char *out, guint64 qword, char punct); /** * bytes_to_hexstr() * * Output hex representation of guint8 array, and return pointer after last character. * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least len * 2 bytes in the buffer. */ WS_DLL_PUBLIC char *bytes_to_hexstr(char *out, const guint8 *ad, size_t len); /** * bytes_to_hexstr_punct() * * Output hex representation of guint8 array, and return pointer after last character. * Each byte will be separated with punct character (cannot be NUL). * It will always output full representation (padded with 0). * * String is not NUL terminated by this routine. * There needs to be at least len * 3 - 1 bytes in the buffer. */ WS_DLL_PUBLIC char *bytes_to_hexstr_punct(char *out, const guint8 *ad, size_t len, char punct); /** Turn an array of bytes into a string showing the bytes in hex, * separated by a punctuation character. * * @param scope memory allocation scheme used * @param buf A pointer to the byte array * @param buf_size The length of the byte array * @param punct The punctuation character * @param max_bytes_len Maximum number of bytes to represent, zero for no limit. * @return A pointer to the formatted string */ WS_DLL_PUBLIC char *bytes_to_str_punct_maxlen(wmem_allocator_t *scope, const guint8 *buf, size_t buf_size, char punct, size_t max_bytes_len); #define bytes_to_str_punct(scope, buf, buf_size, punct) \ bytes_to_str_punct_maxlen(scope, buf, buf_size, punct, 24) /** Turn an array of bytes into a string showing the bytes in hex. * * @param scope memory allocation scheme used * @param buf A pointer to the byte array * @param buf_size The length of the byte array * @param max_bytes_len Maximum number of bytes to represent, zero for no limit. * @return A pointer to the formatted string */ WS_DLL_PUBLIC char *bytes_to_str_maxlen(wmem_allocator_t *scope, const guint8 *buf, size_t buf_size, size_t max_bytes_len); #define bytes_to_str(scope, buf, buf_size) \ bytes_to_str_maxlen(scope, buf, buf_size, 36) /** * oct_to_str_back() * * Output guint32 octal representation backward (last character will be written on ptr - 1), * and return pointer to first character. * * String is not NUL terminated by this routine. * There needs to be at least 12 bytes in the buffer. */ WS_DLL_PUBLIC char *oct_to_str_back(char *ptr, guint32 value); /** * oct64_to_str_back() * * Output guint64 octal representation backward (last character will be written on ptr - 1), * and return pointer to first character. * * String is not NUL terminated by this routine. * There needs to be at least 12 bytes in the buffer. */ WS_DLL_PUBLIC char *oct64_to_str_back(char *ptr, guint64 value); /** * hex_to_str_back() * * Output guint32 hex representation backward (last character will be written on ptr - 1), * and return pointer to first character. * This routine will output for sure (can output more) 'len' decimal characters (number padded with '0'). * * String is not NUL terminated by this routine. * There needs to be at least 2 + MAX(8, len) bytes in the buffer. */ WS_DLL_PUBLIC char *hex_to_str_back_len(char *ptr, guint32 value, int len); /** * hex64_to_str_back() * * Output guint64 hex representation backward (last character will be written on ptr - 1), * and return pointer to first character. * This routine will output for sure (can output more) 'len' decimal characters (number padded with '0'). * * String is not NUL terminated by this routine. * There needs to be at least 2 + MAX(16, len) bytes in the buffer. */ WS_DLL_PUBLIC char *hex64_to_str_back_len(char *ptr, guint64 value, int len); /** * uint_to_str_back() * * Output guint32 decimal representation backward (last character will be written on ptr - 1), * and return pointer to first character. * * String is not NUL terminated by this routine. * There needs to be at least 10 bytes in the buffer. */ WS_DLL_PUBLIC char *uint_to_str_back(char *ptr, guint32 value); /** * uint64_str_back() * * Output guint64 decimal representation backward (last character will be written on ptr - 1), * and return pointer to first character. * * String is not NUL terminated by this routine. * There needs to be at least 20 bytes in the buffer. */ WS_DLL_PUBLIC char *uint64_to_str_back(char *ptr, guint64 value); /** * uint_to_str_back_len() * * Output guint32 decimal representation backward (last character will be written on ptr - 1), * and return pointer to first character. * This routine will output for sure (can output more) 'len' decimal characters (number padded with '0'). * * String is not NUL terminated by this routine. * There needs to be at least MAX(10, len) bytes in the buffer. */ WS_DLL_PUBLIC char *uint_to_str_back_len(char *ptr, guint32 value, int len); /** * uint64_to_str_back_len() * * Output guint64 decimal representation backward (last character will be written on ptr - 1), * and return pointer to first character. * This routine will output for sure (can output more) 'len' decimal characters (number padded with '0'). * * String is not NUL terminated by this routine. * There needs to be at least MAX(20, len) bytes in the buffer. */ WS_DLL_PUBLIC char *uint64_to_str_back_len(char *ptr, guint64 value, int len); /** * int_to_str_back() * * Output gint32 decimal representation backward (last character will be written on ptr - 1), * and return pointer to first character. * * String is not NUL terminated by this routine. * There needs to be at least 11 bytes in the buffer. */ WS_DLL_PUBLIC char *int_to_str_back(char *ptr, gint32 value); /** * int64_to_str_back() * * Output gint64 decimal representation backward (last character will be written on ptr - 1), * and return pointer to first character. * * String is not NUL terminated by this routine. * There needs to be at least 21 bytes in the buffer. */ WS_DLL_PUBLIC char *int64_to_str_back(char *ptr, gint64 value); WS_DLL_PUBLIC void guint32_to_str_buf(guint32 u, gchar *buf, size_t buf_len); WS_DLL_PUBLIC void guint64_to_str_buf(guint64 u, gchar *buf, size_t buf_len); WS_DLL_PUBLIC void ip_to_str_buf(const guint8 *ad, gchar *buf, const int buf_len); WS_DLL_PUBLIC char *ip_to_str(wmem_allocator_t *scope, const guint8 *ad); /* Returns length of the result. */ WS_DLL_PUBLIC void ip6_to_str_buf(const ws_in6_addr *ad, gchar *buf, size_t buf_size); WS_DLL_PUBLIC char *ip6_to_str(wmem_allocator_t *scope, const ws_in6_addr *ad); WS_DLL_PUBLIC gchar *ipxnet_to_str_punct(wmem_allocator_t *scope, const guint32 ad, const char punct); WS_DLL_PUBLIC gchar *eui64_to_str(wmem_allocator_t *scope, const guint64 ad); WS_DLL_PUBLIC void display_epoch_time(gchar *, size_t, const time_t, gint32, const ws_tsprec_e); WS_DLL_PUBLIC void display_signed_time(gchar *, size_t, const gint64, gint32, const ws_tsprec_e); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __TO_STR_H__ */
C
wireshark/wsutil/type_util.c
/* type_util.c * Types utility routines * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "type_util.h" /* * guint64 to gdouble conversions taken from gstutils.c of GStreamer project * * GStreamer * Copyright (C) 1999,2000 Erik Walthinsen <[email protected]> * 2000 Wim Taymans <[email protected]> * 2002 Thomas Vander Stichele <[email protected]> * * gstutils.h: Header for various utility functions * * GNU GPL v2 * */ /* work around error C2520: conversion from unsigned __int64 to double * not implemented, use signed __int64 * * These are implemented as functions because on some platforms a 64bit int to * double conversion is not defined/implemented. */ gdouble type_util_guint64_to_gdouble(guint64 value) { if (value & G_GUINT64_CONSTANT (0x8000000000000000)) return (gdouble) ((gint64) value) + (gdouble) 18446744073709551616.; else return (gdouble) ((gint64) value); } guint64 type_util_gdouble_to_guint64(gdouble value) { if (value < (gdouble) 9223372036854775808.) /* 1 << 63 */ return ((guint64) ((gint64) value)); value -= (gdouble) 18446744073709551616.; return ((guint64) ((gint64) value)); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local Variables: * c-basic-offset: 2 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=2 tabstop=8 expandtab: * :indentSize=2:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/type_util.h
/** @file * Types utility definitions * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __TYPE_UTIL_H__ #define __TYPE_UTIL_H__ #include <glib.h> #include "ws_symbol_export.h" /* * guint64 to gdouble conversions taken from gstutils.h of GStreamer project * * GStreamer * Copyright (C) 1999,2000 Erik Walthinsen <[email protected]> * 2000 Wim Taymans <[email protected]> * 2002 Thomas Vander Stichele <[email protected]> * * gstutils.h: Header for various utility functions * * GNU GPL v2 * */ WS_DLL_PUBLIC guint64 type_util_gdouble_to_guint64(gdouble value); WS_DLL_PUBLIC gdouble type_util_guint64_to_gdouble(guint64 value); #ifdef _WIN32 #define gdouble_to_guint64(value) type_util_gdouble_to_guint64(value) #define guint64_to_gdouble(value) type_util_guint64_to_gdouble(value) #else #define gdouble_to_guint64(value) ((guint64)(value)) #define guint64_to_gdouble(value) ((gdouble)(value)) #endif #endif /* __TYPE_UTIL_H__ */
C
wireshark/wsutil/unicode-utils.c
/* unicode-utils.c * Unicode utility routines * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2006 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "unicode-utils.h" int ws_utf8_seqlen[256] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0x00...0x0f */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0x10...0x1f */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0x20...0x2f */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0x30...0x3f */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0x40...0x4f */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0x50...0x5f */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0x60...0x6f */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0x70...0x7f */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x80...0x8f */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x90...0x9f */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xa0...0xaf */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xb0...0xbf */ 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2, /* 0xc0...0xcf */ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, /* 0xd0...0xdf */ 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, /* 0xe0...0xef */ 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, /* 0xf0...0xff */ }; /* Given a pointer and a length, validates a string of bytes as UTF-8. * Returns the number of valid bytes, and a pointer immediately past * the checked region. * * Differs from Glib's g_utf8_validate_len in that null bytes are * considered valid UTF-8, and that maximal subparts are replaced as * a unit. (I.e., given a sequence of 2 or 3 bytes which are a * truncated version of a 3 or 4 byte UTF-8 character, but the next * byte does not continue the character, the set of 2 or 3 bytes * are replaced with one REPLACMENT CHARACTER.) */ static inline size_t utf_8_validate(const guint8 *start, ssize_t length, const guint8 **end) { const guint8 *ptr = start; guint8 ch; size_t unichar_len, valid_bytes = 0; while (length > 0) { ch = *ptr; if (ch < 0x80) { valid_bytes++; ptr++; length--; continue; } ch = *ptr; if (ch < 0xc2 || ch > 0xf4) { ptr++; length--; *end = ptr; return valid_bytes; } if (ch < 0xe0) { /* 110xxxxx, 2 byte char */ unichar_len = 2; } else if (ch < 0xf0) { /* 1110xxxx, 3 byte char */ unichar_len = 3; ptr++; length--; if (length < 1) { *end = ptr; return valid_bytes; } switch (ch) { case 0xe0: if (*ptr < 0xa0 || *ptr > 0xbf) { *end = ptr; return valid_bytes; } break; case 0xed: if (*ptr < 0x80 || *ptr > 0x9f) { *end = ptr; return valid_bytes; } break; default: if (*ptr < 0x80 || *ptr > 0xbf) { *end = ptr; return valid_bytes; } } } else { /* 11110xxx, 4 byte char - > 0xf4 excluded above */ unichar_len = 4; ptr++; length--; if (length < 1) { *end = ptr; return valid_bytes; } switch (ch) { case 0xf0: if (*ptr < 0x90 || *ptr > 0xbf) { *end = ptr; return valid_bytes; } break; case 0xf4: if (*ptr < 0x80 || *ptr > 0x8f) { *end = ptr; return valid_bytes; } break; default: if (*ptr < 0x80 || *ptr > 0xbf) { *end = ptr; return valid_bytes; } } ptr++; length--; if (length < 1) { *end = ptr; return valid_bytes; } if (*ptr < 0x80 || *ptr > 0xbf) { *end = ptr; return valid_bytes; } } ptr++; length--; if (length < 1) { *end = ptr; return valid_bytes; } if (*ptr < 0x80 || *ptr > 0xbf) { *end = ptr; return valid_bytes; } else { ptr++; length--; valid_bytes += unichar_len; } } *end = ptr; return valid_bytes; } /* * Given a wmem scope, a pointer, and a length, treat the string of bytes * referred to by the pointer and length as a UTF-8 string, and return a * pointer to a UTF-8 string, allocated using the wmem scope, with all * ill-formed sequences replaced with the Unicode REPLACEMENT CHARACTER * according to the recommended "best practices" given in the Unicode * Standard and specified by W3C/WHATWG. * * Note that in conformance with the Unicode Standard, this treats three * byte sequences corresponding to UTF-16 surrogate halves (paired or unpaired) * and two byte overlong encodings of 7-bit ASCII characters as invalid and * substitutes REPLACEMENT CHARACTER for them. Explicit support for nonstandard * derivative encoding formats (e.g. CESU-8, Java Modified UTF-8, WTF-8) could * be added later. * * Compared with g_utf8_make_valid(), this function does not consider * internal NUL bytes as invalid and replace them with replacment characters. * It also replaces maximal subparts as a unit; i.e., a sequence of 2 or 3 * bytes which are a truncated version of a valid 3 or 4 byte character (but * the next byte does not continue the character) are replaced with a single * REPLACEMENT CHARACTER, whereas the Glib function replaces each byte of the * sequence with its own (3 octet) REPLACEMENT CHARACTER. * * XXX: length should probably be a size_t instead of a gint in all * these encoding functions * XXX: the buffer returned can be of different length than the input, * and can have internal NULs as well (so that strlen doesn't give its * length). As with the other encoding functions, we should return the * length of the output buffer (or a wmem_strbuf_t directly) and an * indication of whether there was an invalid character (i.e. * REPLACEMENT CHARACTER was used.) */ wmem_strbuf_t * ws_utf8_make_valid_strbuf(wmem_allocator_t *scope, const guint8 *ptr, ssize_t length) { wmem_strbuf_t *str; str = wmem_strbuf_new_sized(scope, length+1); /* See the Unicode Standard conformance chapter at * https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf especially * Table 3-7 "Well-Formed UTF-8 Byte Sequences" and * U+FFFD Substitution of Maximal Subparts. */ while (length > 0) { const guint8 *prev = ptr; size_t valid_bytes = utf_8_validate(prev, length, &ptr); if (valid_bytes) { wmem_strbuf_append_len(str, prev, valid_bytes); } length -= ptr - prev; prev += valid_bytes; if (ptr - prev) { wmem_strbuf_append_unichar_repl(str); } } return str; } guint8 * ws_utf8_make_valid(wmem_allocator_t *scope, const guint8 *ptr, ssize_t length) { wmem_strbuf_t *str = ws_utf8_make_valid_strbuf(scope, ptr, length); return wmem_strbuf_finalize(str); } #ifdef _WIN32 #include <strsafe.h> /** @file * Unicode utilities (internal interface) * * We define UNICODE and _UNICODE under Windows. This means that * Windows SDK routines expect UTF-16 strings, in contrast to newer * versions of Glib and GTK+ which expect UTF-8. This module provides * convenience routines for converting between UTF-8 and UTF-16. */ #define INITIAL_UTFBUF_SIZE 128 /* * XXX - Should we use g_utf8_to_utf16() and g_utf16_to_utf8() * instead? The goal of the functions below was to provide simple * wrappers for UTF-8 <-> UTF-16 conversion without making the * caller worry about freeing up memory afterward. */ /* Convert from UTF-8 to UTF-16. */ const wchar_t * utf_8to16(const char *utf8str) { static wchar_t *utf16buf[3]; static int utf16buf_len[3]; static int idx; if (utf8str == NULL) return NULL; idx = (idx + 1) % 3; /* * Allocate the buffer if it's not already allocated. */ if (utf16buf[idx] == NULL) { utf16buf_len[idx] = INITIAL_UTFBUF_SIZE; utf16buf[idx] = g_malloc(utf16buf_len[idx] * sizeof(wchar_t)); } while (MultiByteToWideChar(CP_UTF8, 0, utf8str, -1, NULL, 0) >= utf16buf_len[idx]) { /* * Double the buffer's size if it's not big enough. * The size of the buffer starts at 128, so doubling its size * adds at least another 128 bytes, which is more than enough * for one more character plus a terminating '\0'. */ utf16buf_len[idx] *= 2; utf16buf[idx] = g_realloc(utf16buf[idx], utf16buf_len[idx] * sizeof(wchar_t)); } if (MultiByteToWideChar(CP_UTF8, 0, utf8str, -1, utf16buf[idx], utf16buf_len[idx]) == 0) return NULL; return utf16buf[idx]; } void utf_8to16_snprintf(TCHAR *utf16buf, gint utf16buf_len, const gchar* fmt, ...) { va_list ap; gchar* dst; va_start(ap,fmt); dst = ws_strdup_vprintf(fmt, ap); va_end(ap); StringCchPrintf(utf16buf, utf16buf_len, _T("%s"), utf_8to16(dst)); g_free(dst); } /* Convert from UTF-16 to UTF-8. */ gchar * utf_16to8(const wchar_t *utf16str) { static gchar *utf8buf[3]; static int utf8buf_len[3]; static int idx; if (utf16str == NULL) return NULL; idx = (idx + 1) % 3; /* * Allocate the buffer if it's not already allocated. */ if (utf8buf[idx] == NULL) { utf8buf_len[idx] = INITIAL_UTFBUF_SIZE; utf8buf[idx] = g_malloc(utf8buf_len[idx]); } while (WideCharToMultiByte(CP_UTF8, 0, utf16str, -1, NULL, 0, NULL, NULL) >= utf8buf_len[idx]) { /* * Double the buffer's size if it's not big enough. * The size of the buffer starts at 128, so doubling its size * adds at least another 128 bytes, which is more than enough * for one more character plus a terminating '\0'. */ utf8buf_len[idx] *= 2; utf8buf[idx] = g_realloc(utf8buf[idx], utf8buf_len[idx]); } if (WideCharToMultiByte(CP_UTF8, 0, utf16str, -1, utf8buf[idx], utf8buf_len[idx], NULL, NULL) == 0) return NULL; return utf8buf[idx]; } /* Convert our argument list from UTF-16 to UTF-8. */ char ** arg_list_utf_16to8(int argc, wchar_t *wc_argv[]) { char **argv; int i; argv = (char **)g_malloc((argc + 1) * sizeof(char *)); for (i = 0; i < argc; i++) { argv[i] = g_utf16_to_utf8(wc_argv[i], -1, NULL, NULL, NULL); } argv[argc] = NULL; return argv; } #endif /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/unicode-utils.h
/* unicode-utils.h * Unicode utility definitions * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2006 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __UNICODEUTIL_H__ #define __UNICODEUTIL_H__ #include <wireshark.h> #ifdef _WIN32 #include <windows.h> #include <tchar.h> #include <wchar.h> #endif /** * @file * Unicode convenience routines. */ #ifdef __cplusplus extern "C" { #endif #ifdef WS_DEBUG_UTF_8 #define DEBUG_UTF_8_ENABLED true #else #define DEBUG_UTF_8_ENABLED false #endif #define _CHECK_UTF_8(level, str, len) \ do { \ const char *__uni_endptr; \ if (DEBUG_UTF_8_ENABLED && (str) != NULL && \ !g_utf8_validate(str, len, &__uni_endptr)) { \ ws_log_utf8(str, len, __uni_endptr); \ } \ } while (0) #define WS_UTF_8_CHECK(str, len) \ _CHECK_UTF_8(LOG_LEVEL_DEBUG, str, len) #define WS_UTF_8_DEBUG_HERE(str, len) \ _CHECK_UTF_8(LOG_LEVEL_ECHO, str, len) WSUTIL_EXPORT int ws_utf8_seqlen[256]; /** Given the first byte in an UTF-8 encoded code point, * return the length of the multibyte sequence, or *ZERO* * if the byte is invalid as the first byte in a multibyte * sequence. */ #define ws_utf8_char_len(ch) (ws_utf8_seqlen[(ch)]) /* * Given a wmem scope, a pointer, and a length, treat the string of bytes * referred to by the pointer and length as a UTF-8 string, and return a * pointer to a UTF-8 string, allocated using the wmem scope, with all * ill-formed sequences replaced with the Unicode REPLACEMENT CHARACTER * according to the recommended "best practices" given in the Unicode * Standard and specified by W3C/WHATWG. */ WS_DLL_PUBLIC guint8 * ws_utf8_make_valid(wmem_allocator_t *scope, const guint8 *ptr, ssize_t length); /* * Same as ws_utf8_make_valid() but returns a wmem_strbuf_t. */ WS_DLL_PUBLIC wmem_strbuf_t * ws_utf8_make_valid_strbuf(wmem_allocator_t *scope, const guint8 *ptr, ssize_t length); #ifdef _WIN32 /** Given a UTF-8 string, convert it to UTF-16. This is meant to be used * to convert between GTK+ 2.x (UTF-8) to Windows (UTF-16). * * @param utf8str The string to convert. May be NULL. * @return The string converted to UTF-16. If utf8str is NULL, returns * NULL. The return value should NOT be freed by the caller. */ WS_DLL_PUBLIC const wchar_t * utf_8to16(const char *utf8str); /** Create a UTF-16 string (in place) according to the format string. * * @param utf16buf The buffer to return the UTF-16 string in. * @param utf16buf_len The size of the 'utf16buf' parameter * @param fmt A standard printf() format string */ WS_DLL_PUBLIC void utf_8to16_snprintf(TCHAR *utf16buf, gint utf16buf_len, const gchar* fmt, ...) G_GNUC_PRINTF(3, 4); /** Given a UTF-16 string, convert it to UTF-8. This is meant to be used * to convert between GTK+ 2.x (UTF-8) to Windows (UTF-16). * * @param utf16str The string to convert. May be NULL. * @return The string converted to UTF-8. If utf16str is NULL, returns * NULL. The return value should NOT be freed by the caller. */ WS_DLL_PUBLIC gchar * utf_16to8(const wchar_t *utf16str); /** Convert the supplied program argument list from UTF-16 to UTF-8 * return a pointer to the array of UTF-8 arguments. This is intended * to be used to normalize command line arguments at program startup. * * @param argc The number of arguments. * @param argv The argument values (vector). */ WS_DLL_PUBLIC char **arg_list_utf_16to8(int argc, wchar_t *wc_argv[]); #endif /* _WIN32 */ /* * defines for helping with UTF-16 surrogate pairs */ #define IS_LEAD_SURROGATE(uchar2) \ ((uchar2) >= 0xd800 && (uchar2) < 0xdc00) #define IS_TRAIL_SURROGATE(uchar2) \ ((uchar2) >= 0xdc00 && (uchar2) < 0xe000) #define SURROGATE_VALUE(lead, trail) \ (((((lead) - 0xd800) << 10) | ((trail) - 0xdc00)) + 0x10000) #ifdef __cplusplus } #endif #endif /* __UNICODEUTIL_H__ */
C/C++
wireshark/wsutil/utf8_entities.h
/** @file * * Byte sequences for various UTF-8 entities * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __UTF8_ENTITIES_H__ #define __UTF8_ENTITIES_H__ /* * Sequences can be found at * http://www.fileformat.info/info/unicode/ * http://www.utf8-chartable.de/ * and other places * * Please be conservative when adding code points below. While many modern * systems default to UTF-8 and handle it well, some do not. The Windows * console is a notable example. As a general rule you probably shouldn't * stray too far from code page 437 or WGL4: * https://en.wikipedia.org/wiki/Code_page_437 * https://en.wikipedia.org/wiki/Windows_Glyph_List_4 * * Hopefully we can dispense with the sequences below and simply encode our * files as UTF 8 at some point. For example gcc has supported UTF 8 since * at least 3.4. Visual C++ on the other hand is much more problematic. * 2015 and later support /source-charset:utf-8, but prior versions appear * to require a UTF 8 BOM. */ #define UTF8_DEGREE_SIGN "\xc2\xb0" /* 176 / 0xb0 */ #define UTF8_SUPERSCRIPT_TWO "\xc2\xb2" /* 178 / 0xb2 */ #define UTF8_MICRO_SIGN "\xc2\xb5" /* 181 / 0xb5 */ #define UTF8_MIDDLE_DOT "\xc2\xb7" /* 183 / 0xb7 */ #define UTF8_RIGHT_POINTING_DOUBLE_ANGLE_QUOTATION_MARK "\xc2\xbb" /* 187 / 0xbb */ #define UTF8_BULLET "\xe2\x80\xa2" /* 8226 / 0x2024 */ #define UTF8_EM_DASH "\xe2\x80\x94" /* 8212 / 0x2014 */ #define UTF8_HORIZONTAL_ELLIPSIS "\xe2\x80\xa6" /* 8230 / 0x2026 */ #define UTF8_LEFTWARDS_ARROW "\xe2\x86\x90" /* 8592 / 0x2190 */ #define UTF8_RIGHTWARDS_ARROW "\xe2\x86\x92" /* 8594 / 0x2192 */ #define UTF8_LEFT_RIGHT_ARROW "\xe2\x86\x94" /* 8596 / 0x2194 */ /* macOS command key */ #define UTF8_PLACE_OF_INTEREST_SIGN "\xe2\x8c\x98" /* 8984 / 0x2318 */ #define UTF8_SYMBOL_FOR_NULL "\xe2\x90\x80" /* 9216 / 0x2400 */ #define UTF8_CHECK_MARK "\xe2\x9c\x93" /* 10003 / 0x2713 */ #define UTF8_BALLOT_X "\xe2\x9c\x97" /* 10007 / 0x2717 */ #define UTF8_LONG_RIGHTWARDS_ARROW "\xe2\x9f\xb6" /* 10230 / 0x27f6 */ #define UTF8_ZERO_WIDTH_NO_BREAK_SPACE "\xef\xbb\xbf" /* 65279 / 0xffef */ #define UTF8_BOM UTF8_ZERO_WIDTH_NO_BREAK_SPACE #endif /* __UTF8_ENTITIES_H__ */ /* * 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: */
C
wireshark/wsutil/version_info.c
/* version_info.c * Routines to report version information for Wireshark programs * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <config.h> #include "version_info.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #ifdef _WIN32 #include <windows.h> #elif __APPLE__ #include <sys/types.h> #include <sys/sysctl.h> #elif __linux__ #include <sys/sysinfo.h> #endif #include <glib.h> #include <pcre2.h> #ifdef HAVE_ZLIB #include <zlib.h> #endif #include "vcs_version.h" #include <wsutil/cpu_info.h> #include <wsutil/os_version_info.h> #include <wsutil/crash_info.h> #include <wsutil/plugins.h> static char *appname_with_version; static char *copyright_info; static char *license_info; static char *comp_info; static char *runtime_info; static void end_string(GString *str); static void get_compiler_info(GString *str); static void get_mem_info(GString *str); void ws_init_version_info(const char *appname, gather_feature_func gather_compile, gather_feature_func gather_runtime) { GString *comp_info_str, *runtime_info_str; GString *copyright_info_str; GString *license_info_str; copyright_info_str = g_string_new(get_copyright_info()); end_string(copyright_info_str); copyright_info = g_string_free(copyright_info_str, FALSE); license_info_str = g_string_new(get_license_info_short()); end_string(license_info_str); license_info = g_string_free(license_info_str, FALSE); /* * Combine the supplied application name string with the * version - including the VCS version, for a build from * a checkout. */ if (strstr(appname, "Wireshark") != NULL) { appname_with_version = ws_strdup_printf("%s %s", appname, get_ws_vcs_version_info()); } else { appname_with_version = ws_strdup_printf("%s (Wireshark) %s", appname, get_ws_vcs_version_info()); } /* Get the compile-time version information string */ comp_info_str = get_compiled_version_info(gather_compile); /* Get the run-time version information string */ runtime_info_str = get_runtime_version_info(gather_runtime); comp_info = g_string_free(comp_info_str, FALSE); runtime_info = g_string_free(runtime_info_str, FALSE); /* Add this information to the information to be reported on a crash. */ ws_add_crash_info("%s\n" "\n" "%s\n" "%s", appname_with_version, comp_info, runtime_info); } /* * Take the gathered list of present/absent features (dependencies) * and add them to the given string. * Callback function for g_list_foreach() used in * get_compiled_version_info() and get_runtime_version_info(). */ static void feature_to_gstring(gpointer data, gpointer user_data) { gchar *feature = (gchar *)data; GString *str = (GString *)user_data; if (str->len > 0) { g_string_append(str, ", "); } g_string_append_printf(str, "%s %s", (*feature == '+' ? "with" : "without"), feature + 1); } /* * If the string doesn't end with a newline, append one. * Then word-wrap it to 80 columns. */ static void end_string(GString *str) { size_t point; char *p, *q; point = str->len; if (point == 0 || str->str[point - 1] != '\n') g_string_append(str, "\n"); p = str->str; while (*p != '\0') { q = strchr(p, '\n'); if (q - p > 80) { /* * Break at or before this point. */ q = p + 80; while (q > p && *q != ' ') q--; if (q != p) *q = '\n'; } p = q + 1; } } const char * get_appname_and_version(void) { return appname_with_version; } void gather_pcre2_compile_info(feature_list l) { with_feature(l, "PCRE2"); } void gather_zlib_compile_info(feature_list l) { #ifdef HAVE_ZLIB #ifdef ZLIB_VERSION with_feature(l, "zlib "ZLIB_VERSION); #else with_feature(l, "zlib (version unknown)"); #endif /* ZLIB_VERSION */ #else without_feature(l, "zlib"); #endif /* HAVE_ZLIB */ } /* * Get various library compile-time versions, put them in a GString, * and return the GString. */ GString * get_compiled_version_info(gather_feature_func gather_compile) { GString *str; GList *l = NULL; str = g_string_new("Compiled "); g_string_append_printf(str, "(%d-bit) ", (int)sizeof(str) * 8); /* Compiler info */ g_string_append(str, "using "); get_compiler_info(str); #ifdef GLIB_MAJOR_VERSION with_feature(&l, "GLib %d.%d.%d", GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION); #else with_feature(&l, "GLib (version unknown)"); #endif if (gather_compile != NULL) { gather_compile(&l); } l = g_list_reverse(l); g_list_foreach(l, feature_to_gstring, str); #ifdef HAVE_PLUGINS g_string_append(str, ", with binary plugins"); #else g_string_append(str, ", without binary plugins"); #endif #ifdef WS_DEBUG g_string_append(str, ", debug build"); #else g_string_append(str, ", release build"); #endif #ifdef WS_DEBUG_UTF_8 g_string_append(str, " (+utf8)"); #endif g_string_append(str, "."); end_string(str); free_features(&l); return str; } static void get_mem_info(GString *str) { gint64 memsize = 0; #ifdef _WIN32 MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); if (GlobalMemoryStatusEx(&statex)) memsize = statex.ullTotalPhys; #elif __APPLE__ size_t len = sizeof(memsize); sysctlbyname("hw.memsize", &memsize, &len, NULL, 0); #elif __linux__ struct sysinfo info; if (sysinfo(&info) == 0) memsize = info.totalram * info.mem_unit; #endif if (memsize > 0) g_string_append_printf(str, ", with %" G_GINT64_FORMAT " MB of physical memory", memsize/(1024*1024)); } /* * Get compiler information, and append it to the GString. */ static void get_compiler_info(GString *str) { /* * See https://sourceforge.net/apps/mediawiki/predef/index.php?title=Compilers * information on various defined strings. * * GCC's __VERSION__ is a nice text string for humans to * read. The page at sourceforge.net largely describes * numeric #defines that encode the version; if the compiler * doesn't also offer a nice printable string, we try prettifying * the number somehow. */ #if defined(_MSC_FULL_VER) /* * We check for this first, as Microsoft have a version of their * compiler that has Clang as the front end and their code generator * as the back end. * * My head asplode. */ /* As of Wireshark 3.0, we support only Visual Studio 2015 (14.x) * or later. * * https://dev.to/yumetodo/list-of-mscver-and-mscfullver-8nd * has a *large* table of Microsoft product names, VC++ versions, * _MSC_VER values, and _MSC_FULL_VER values. All the versions * we support define _MSC_FULL_VER. We don't bother trying to * get the SP/update/version number from the build number, as * we'd have to keep updating that with every update; there's no * way to get that information directly from a predefine, and in * some cases multiple updates/versions have the *same* build * number (because they didn't update the toolchain). * * https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=vs-2017 * defines the format of _MSC_VER and _MSC_FULL_VER. _MSC_FULL_VER * is a decimal number of the form MMmmBBBBB, where MM is the compiler/ * toolchain major version, mm is the minor version, and BBBBB is the * build. We break it down based on that. */ #define COMPILER_MAJOR_VERSION (_MSC_FULL_VER / 10000000) #define COMPILER_MINOR_VERSION ((_MSC_FULL_VER % 10000000) / 100000) #define COMPILER_BUILD_NUMBER (_MSC_FULL_VER % 100000) /* * From https://web.archive.org/web/20190125151548/https://blogs.msdn.microsoft.com/vcblog/2014/11/17/c111417-features-in-vs-2015-preview/ * Bakersfield: DevDiv's upper management determines the scheduling * of new major versions. They also decided to increment the product * version from 12 (for VS 2013) to 14 (for VS 2015). However, the * C++ compiler's version incremented normally, from 18 to 19. * (It's larger because the C++ compiler predates the "Visual" in * Visual C++.) * * So the product version number is 5 less than the compiler version * number. */ #define VCPP_MAJOR_VERSION (COMPILER_MAJOR_VERSION - 5) #if VCPP_MAJOR_VERSION == 14 /* * From https://devblogs.microsoft.com/cppblog/side-by-side-minor-version-msvc-toolsets-in-visual-studio-2017/ * * We've been delivering improvements to Visual Studio 2017 more * frequently than ever before. Since its first release in March * we've released four major updates to VS2017 and are currently * previewing the fifth update, VS2017 version 15.5. * * The MSVC toolset in VS2017 is built as a minor version update to * the VS2015 compiler toolset. This minor version bump indicates * that the VS2017 MSVC toolset is binary compatible with the VS2015 * MSVC toolset, enabling an easier upgrade for VS2015 users. Even * though the MSVC compiler toolset in VS2017 delivers many new * features and conformance improvements it is a minor version, * compatible update from 14.00 in VS2015 to 14.10 in VS2017. */ #if COMPILER_MINOR_VERSION < 10 #define VS_VERSION "2015" #elif COMPILER_MINOR_VERSION < 20 #define VS_VERSION "2017" #elif COMPILER_MINOR_VERSION < 30 #define VS_VERSION "2019" #else #define VS_VERSION "2022" #endif #else /* * Add additional checks here, before the #else. */ #define VS_VERSION "(unknown)" #endif /* VCPP_MAJOR_VERSION */ /* * XXX - should we show the raw compiler version number, as is * shown by "cl /?", which would be %d.%d.%d.%d with * COMPILER_MAJOR_VERSION, COMPILER_MINOR_VERSION, * COMPILER_BUILD_NUMBER, and _MSC_BUILD, the last of which is * "the revision number element of the compiler's version number", * which I guess is not to be confused with the build number, * the _BUILD in the name nonwithstanding. */ g_string_append_printf(str, "Microsoft Visual Studio " VS_VERSION " (VC++ %d.%d, build %d)", VCPP_MAJOR_VERSION, COMPILER_MINOR_VERSION, COMPILER_BUILD_NUMBER); #if defined(__clang__) /* * See above. */ g_string_append_printf(str, " clang/C2 %s and -fno-ms-compatibility", __VERSION__); #endif #elif defined(__GNUC__) && defined(__VERSION__) /* * Clang and llvm-gcc also define __GNUC__ and __VERSION__; * distinguish between them. */ #if defined(__clang__) /* clang */ gchar *version; /* clang's version string has a trailing space. */ #if defined(__clang_version__) version = g_strdup(__clang_version__); g_string_append_printf(str, "Clang %s", g_strstrip(version)); #else version = g_strdup(__VERSION__); g_string_append_printf(str, "%s", g_strstrip(version)); #endif /* __clang_version__ */ g_free(version); #elif defined(__llvm__) /* llvm-gcc */ g_string_append_printf(str, "llvm-gcc %s", __VERSION__); #else /* boring old GCC */ g_string_append_printf(str, "GCC %s", __VERSION__); #endif #elif defined(__HP_aCC) g_string_append_printf(str, "HP aCC %d", __HP_aCC); #elif defined(__xlC__) g_string_append_printf(str, "IBM XL C %d.%d", (__xlC__ >> 8) & 0xFF, __xlC__ & 0xFF); #ifdef __IBMC__ if ((__IBMC__ % 10) != 0) g_string_append_printf(str, " patch %d", __IBMC__ % 10); #endif /* __IBMC__ */ #elif defined(__INTEL_COMPILER) g_string_append_printf(str, "Intel C %d.%d", __INTEL_COMPILER / 100, (__INTEL_COMPILER / 10) % 10); if ((__INTEL_COMPILER % 10) != 0) g_string_append_printf(str, " patch %d", __INTEL_COMPILER % 10); #ifdef __INTEL_COMPILER_BUILD_DATE g_string_sprinta(str, ", compiler built %04d-%02d-%02d", __INTEL_COMPILER_BUILD_DATE / 10000, (__INTEL_COMPILER_BUILD_DATE / 100) % 100, __INTEL_COMPILER_BUILD_DATE % 100); #endif /* __INTEL_COMPILER_BUILD_DATE */ #elif defined(__SUNPRO_C) g_string_append_printf(str, "Sun C %d.%d", (__SUNPRO_C >> 8) & 0xF, (__SUNPRO_C >> 4) & 0xF); if ((__SUNPRO_C & 0xF) != 0) g_string_append_printf(str, " patch %d", __SUNPRO_C & 0xF); #else g_string_append(str, "unknown compiler"); #endif } void gather_pcre2_runtime_info(feature_list l) { /* From pcre2_api(3): * The where argument should point to a buffer that is at least 24 code * units long. (The exact length required can be found by calling * pcre2_config() with where set to NULL.) * * The API should accept a buffer size as additional input. We could opt for a * stack buffer size greater than 24 but let's just go with the weirdness... */ int size; char *buf_pcre2; size = pcre2_config(PCRE2_CONFIG_VERSION, NULL); if (size < 0 || size > 255) { without_feature(l, "PCRE2 (error querying)"); return; } buf_pcre2 = g_malloc(size + 1); pcre2_config(PCRE2_CONFIG_VERSION, buf_pcre2); buf_pcre2[size] = '\0'; with_feature(l, "PCRE2 %s", buf_pcre2); g_free(buf_pcre2); } void gather_zlib_runtime_info(feature_list l) { (void)l; #if defined(HAVE_ZLIB) && !defined(_WIN32) with_feature(l, "zlib %s", zlibVersion()); #endif } /* * Get various library run-time versions, and the OS version, and append * them to the specified GString. * * "additional_info" is called at the end to append any additional * information; this is required in order to, for example, put the * libcap information at the end of the string, as we currently * don't use libcap in TShark. */ GString * get_runtime_version_info(gather_feature_func gather_runtime) { GString *str; gchar *lc; GList *l = NULL; str = g_string_new("Running on "); get_os_version_info(str); /* CPU Info */ get_cpu_info(str); /* Get info about installed memory */ get_mem_info(str); with_feature(&l, "GLib %u.%u.%u", glib_major_version, glib_minor_version, glib_micro_version); if (gather_runtime != NULL) { gather_runtime(&l); } l = g_list_reverse(l); g_list_foreach(l, feature_to_gstring, str); /* * Display LC_CTYPE as a relevant, portable and sort of representative * locale configuration without being exceedingly verbose and including * the whole shebang of categories using LC_ALL. */ if ((lc = setlocale(LC_CTYPE, NULL)) != NULL) { g_string_append_printf(str, ", with LC_TYPE=%s", lc); } #ifdef HAVE_PLUGINS if (plugins_supported()) { g_string_append(str, ", binary plugins supported"); } #endif g_string_append_c(str, '.'); end_string(str); free_features(&l); return str; } /* * Return a version number string for Wireshark, including, for builds * from a tree checked out from Wireshark's version control system, * something identifying what version was checked out. */ const char * get_ws_vcs_version_info(void) { #ifdef VCSVERSION return VERSION " (" VCSVERSION ")"; #else return VERSION; #endif } const char * get_ws_vcs_version_info_short(void) { #ifdef VCSVERSION return VCSVERSION; #else return VERSION; #endif } void get_ws_version_number(int *major, int *minor, int *micro) { if (major) *major = VERSION_MAJOR; if (minor) *minor = VERSION_MINOR; if (micro) *micro = VERSION_MICRO; } void show_version(void) { printf("%s.\n\n" "%s" "%s\n" "%s\n" "%s", appname_with_version, copyright_info, license_info, comp_info, runtime_info); } void show_help_header(const char *description) { printf("%s\n", appname_with_version); if (description) { printf("%s\n", description); printf("See https://www.wireshark.org for more information.\n"); } } /* * Get copyright information. */ const char * get_copyright_info(void) { return "Copyright 1998-2023 Gerald Combs <[email protected]> and contributors."; } const char * get_license_info_short(void) { return "Licensed under the terms of the GNU General Public License (version 2 or later). " "This is free software; see the file named COPYING in the distribution. " "There is NO WARRANTY; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."; } const char * get_license_info(void) { return "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."; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/version_info.h
/** @file * * Declarations of routines to report version information for Wireshark * programs * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_VERSION_INFO_H__ #define __WS_VERSION_INFO_H__ #include <glib.h> #include <wsutil/feature_list.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Initialize information about the program for various purposes, including * reporting the version and build information for the program, putting * that information into crash dumps if possible, and giving the program * name and version information into capture files written by the program * if possible. * * "appname" is a string that appears at the beginning of the information; * it should be the application name. "(Wireshark)" will be added if * the program isn't Wireshark. * * "gather_compile" is called (if non-null) to add any additional build-time * information. * * "gather_runtime" is called (if non-null) to add any additional * run-time information; this is required in order to, for example, * put the libcap information into the string, as we currently * don't use libcap in TShark. */ WS_DLL_PUBLIC void ws_init_version_info(const char *appname, gather_feature_func gather_compile, gather_feature_func gather_runtime); /* * Get a string giving the application name, as provided to * ws_init_version_info(), followed by a string giving the * application version. */ WS_DLL_PUBLIC const char *get_appname_and_version(void); WS_DLL_PUBLIC void gather_pcre2_compile_info(feature_list l); WS_DLL_PUBLIC void gather_zlib_compile_info(feature_list l); /* * Get various library compile-time versions, put them in a GString, * and return the GString. * * "gather_compile" is called (if non-null) to add any additional build-time * information. */ WS_DLL_PUBLIC GString *get_compiled_version_info(gather_feature_func gather_compile); WS_DLL_PUBLIC void gather_pcre2_runtime_info(feature_list l); WS_DLL_PUBLIC void gather_zlib_runtime_info(feature_list l); /* * Get various library run-time versions, and the OS version, put them in * a GString, and return the GString. * * "gather_runtime" is called (if non-null) to add any additional * run-time information; this is required in order to, for example, * put the libcap information into the string, as we currently * don't use libcap in TShark. */ WS_DLL_PUBLIC GString *get_runtime_version_info(gather_feature_func gather_runtime); /* * Return a version number string for Wireshark, including, for builds * from a tree checked out from Wireshark's version control system, * something identifying what version was checked out. */ WS_DLL_PUBLIC const char *get_ws_vcs_version_info(void); /* * Shorter version of get_ws_vcs_version_info(). */ WS_DLL_PUBLIC const char *get_ws_vcs_version_info_short(void); /* * Return version number as integers. */ WS_DLL_PUBLIC void get_ws_version_number(int *major, int *minor, int *micro); /* * Show the program name and version number information on the standard * output; this is used for command-line "show the version" options. */ WS_DLL_PUBLIC void show_version(void); /* * Show the program name and version number information, a supplied * description string, and a "See {URL} for more information" message. * This is used for command-line "help" options. */ WS_DLL_PUBLIC void show_help_header(const char *description); WS_DLL_PUBLIC const char *get_copyright_info(void); WS_DLL_PUBLIC const char *get_license_info(void); WS_DLL_PUBLIC const char *get_license_info_short(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __WS_VERSION_INFO_H__ */
C
wireshark/wsutil/win32-utils.c
/* win32-utils.c * Win32 utility routines * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2006 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <config.h> #include "win32-utils.h" #include <tchar.h> #include <versionhelpers.h> /* Quote the argument element if necessary, so that it will get * reconstructed correctly in the C runtime startup code. Note that * the unquoting algorithm in the C runtime is really weird, and * rather different than what Unix shells do. See stdargv.c in the C * runtime sources (in the Platform SDK, in src/crt). * * Stolen from GLib's protect_argv(), an internal routine that quotes * string in an argument list so that they arguments will be handled * correctly in the command-line string passed to CreateProcess() * if that string is constructed by gluing those strings together. */ gchar * protect_arg (const gchar *argv) { gchar *new_arg; const gchar *p = argv; gchar *q; gint len = 0; gboolean need_dblquotes = FALSE; while (*p) { if (*p == ' ' || *p == '\t') need_dblquotes = TRUE; else if (*p == '"') len++; else if (*p == '\\') { const gchar *pp = p; while (*pp && *pp == '\\') pp++; if (*pp == '"') len++; } len++; p++; } q = new_arg = g_malloc (len + need_dblquotes*2 + 1); p = argv; if (need_dblquotes) *q++ = '"'; while (*p) { if (*p == '"') *q++ = '\\'; else if (*p == '\\') { const gchar *pp = p; while (*pp && *pp == '\\') pp++; if (*pp == '"') *q++ = '\\'; } *q++ = *p; p++; } if (need_dblquotes) *q++ = '"'; *q++ = '\0'; return new_arg; } /* * Generate a UTF-8 string for a Windows error. */ /* * We make the buffer at least this big, under the assumption that doing * so will reduce the number of reallocations to do. (Otherwise, why * did Microsoft bother supporting a minimum buffer size?) */ #define ERRBUF_SIZE 128 const char * win32strerror(DWORD error) { DWORD retval; WCHAR *utf16_message; char *utf8_message; char *tempmsg; const char *msg; /* * XXX - what language ID to use? * * For UN*Xes, g_strerror() may or may not return localized strings. * * We currently don't have localized strings, except for GUI items, * but we might want to do so. On the other hand, if most of these * messages are going to be read by Wireshark developers, English * might be a better choice, so the developer doesn't have to get * the message translated if it's in a language they don't happen * to understand. Then again, we're including the error number, * so the developer can just look that up. */ retval = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&utf16_message, ERRBUF_SIZE, NULL); if (retval == 0) { /* Failed. */ tempmsg = ws_strdup_printf("Couldn't get error message for error (%lu) (because %lu)", error, GetLastError()); msg = g_intern_string(tempmsg); g_free(tempmsg); return msg; } utf8_message = g_utf16_to_utf8(utf16_message, -1, NULL, NULL, NULL); LocalFree(utf16_message); if (utf8_message == NULL) { /* Conversion failed. */ tempmsg = ws_strdup_printf("Couldn't convert error message for error to UTF-8 (%lu) (because %lu)", error, GetLastError()); msg = g_intern_string(tempmsg); g_free(tempmsg); return msg; } tempmsg = ws_strdup_printf("%s (%lu)", utf8_message, error); g_free(utf8_message); msg = g_intern_string(tempmsg); g_free(tempmsg); return msg; } /* * Generate a string for a Win32 exception code. */ const char * win32strexception(DWORD exception) { static char errbuf[ERRBUF_SIZE+1]; static const struct exception_msg { DWORD code; char *msg; } exceptions[] = { { EXCEPTION_ACCESS_VIOLATION, "Access violation" }, { EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array bounds exceeded" }, { EXCEPTION_BREAKPOINT, "Breakpoint" }, { EXCEPTION_DATATYPE_MISALIGNMENT, "Data type misalignment" }, { EXCEPTION_FLT_DENORMAL_OPERAND, "Denormal floating-point operand" }, { EXCEPTION_FLT_DIVIDE_BY_ZERO, "Floating-point divide by zero" }, { EXCEPTION_FLT_INEXACT_RESULT, "Floating-point inexact result" }, { EXCEPTION_FLT_INVALID_OPERATION, "Invalid floating-point operation" }, { EXCEPTION_FLT_OVERFLOW, "Floating-point overflow" }, { EXCEPTION_FLT_STACK_CHECK, "Floating-point stack check" }, { EXCEPTION_FLT_UNDERFLOW, "Floating-point underflow" }, { EXCEPTION_GUARD_PAGE, "Guard page violation" }, { EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal instruction" }, { EXCEPTION_IN_PAGE_ERROR, "Page-in error" }, { EXCEPTION_INT_DIVIDE_BY_ZERO, "Integer divide by zero" }, { EXCEPTION_INT_OVERFLOW, "Integer overflow" }, { EXCEPTION_INVALID_DISPOSITION, "Invalid disposition" }, { EXCEPTION_INVALID_HANDLE, "Invalid handle" }, { EXCEPTION_NONCONTINUABLE_EXCEPTION, "Non-continuable exception" }, { EXCEPTION_PRIV_INSTRUCTION, "Privileged instruction" }, { EXCEPTION_SINGLE_STEP, "Single-step complete" }, { EXCEPTION_STACK_OVERFLOW, "Stack overflow" }, { 0, NULL } }; #define N_EXCEPTIONS (sizeof exceptions / sizeof exceptions[0]) for (size_t i = 0; i < N_EXCEPTIONS; i++) { if (exceptions[i].code == exception) return exceptions[i].msg; } snprintf(errbuf, sizeof errbuf, "Exception 0x%08lx", exception); return errbuf; } // This appears to be the closest equivalent to SIGPIPE on Windows. // https://devblogs.microsoft.com/oldnewthing/?p=2433 // https://stackoverflow.com/a/53214/82195 static void win32_kill_child_on_exit(HANDLE child_handle) { static HANDLE cjo_handle = NULL; if (!cjo_handle) { cjo_handle = CreateJobObject(NULL, NULL); if (!cjo_handle) { ws_log(LOG_DOMAIN_CAPTURE, LOG_LEVEL_DEBUG, "Could not create child cleanup job object: %s", win32strerror(GetLastError())); return; } JOBOBJECT_EXTENDED_LIMIT_INFORMATION cjo_jel_info = { 0 }; cjo_jel_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; BOOL sijo_ret = SetInformationJobObject(cjo_handle, JobObjectExtendedLimitInformation, &cjo_jel_info, sizeof(cjo_jel_info)); if (!sijo_ret) { ws_log(LOG_DOMAIN_CAPTURE, LOG_LEVEL_DEBUG, "Could not set child cleanup limits: %s", win32strerror(GetLastError())); } } BOOL aptjo_ret = AssignProcessToJobObject(cjo_handle, child_handle); if (!aptjo_ret) { ws_log(LOG_DOMAIN_CAPTURE, LOG_LEVEL_DEBUG, "Could not assign child cleanup process: %s", win32strerror(GetLastError())); } } BOOL win32_create_process(const char *application_name, const char *command_line, LPSECURITY_ATTRIBUTES process_attributes, LPSECURITY_ATTRIBUTES thread_attributes, size_t n_inherit_handles, HANDLE *inherit_handles, DWORD creation_flags, LPVOID environment, const char *current_directory, LPSTARTUPINFO startup_info, LPPROCESS_INFORMATION process_information) { gunichar2 *wappname = NULL, *wcurrentdirectory = NULL; gunichar2 *wcommandline = g_utf8_to_utf16(command_line, -1, NULL, NULL, NULL); LPPROC_THREAD_ATTRIBUTE_LIST attribute_list = NULL; STARTUPINFOEX startup_infoex; size_t i; // CREATE_SUSPENDED: Suspend the child so that we can cleanly call // AssignProcessToJobObject. DWORD wcreationflags = creation_flags|CREATE_SUSPENDED; // CREATE_BREAKAWAY_FROM_JOB: The main application might be associated with a job, // e.g. if we're running under "Run As", ConEmu, or Visual Studio. On Windows // <= 7 our child process needs to break away from it so that we can cleanly // call AssignProcessToJobObject on *our* job. // Windows >= 8 supports nested jobs so this isn't necessary there. // https://blogs.msdn.microsoft.com/winsdk/2014/09/22/job-object-insanity/ // if (! IsWindowsVersionOrGreater(6, 2, 0)) { // Windows 8 wcreationflags |= CREATE_BREAKAWAY_FROM_JOB; } if (application_name) { wappname = g_utf8_to_utf16(application_name, -1, NULL, NULL, NULL); } if (current_directory) { wcurrentdirectory = g_utf8_to_utf16(current_directory, -1, NULL, NULL, NULL); } if (n_inherit_handles > 0) { size_t attr_size = 0; BOOL success; success = InitializeProcThreadAttributeList(NULL, 1, 0, &attr_size); if (success || (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { attribute_list = g_malloc(attr_size); success = InitializeProcThreadAttributeList(attribute_list, 1, 0, &attr_size); } if (success && (attribute_list != NULL)) { success = UpdateProcThreadAttribute(attribute_list, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherit_handles, n_inherit_handles * sizeof(HANDLE), NULL, NULL); } if (!success && (attribute_list != NULL)) { DeleteProcThreadAttributeList(attribute_list); g_free(attribute_list); attribute_list = NULL; } } memset(&startup_infoex, 0, sizeof(startup_infoex)); startup_infoex.StartupInfo = *startup_info; startup_infoex.StartupInfo.cb = sizeof(startup_infoex); startup_infoex.lpAttributeList = attribute_list; wcreationflags |= EXTENDED_STARTUPINFO_PRESENT; for (i = 0; i < n_inherit_handles; i++) { SetHandleInformation(inherit_handles[i], HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); } BOOL cp_res = CreateProcess(wappname, wcommandline, process_attributes, thread_attributes, (n_inherit_handles > 0) ? TRUE : FALSE, wcreationflags, environment, wcurrentdirectory, &startup_infoex.StartupInfo, process_information); /* While this function makes the created process inherit only the explicitly * listed handles, there can be other functions (in 3rd party libraries) * that create processes inheriting all inheritable handles. To minimize * number of unwanted handle duplicates (handle duplicate can extend object * lifetime, e.g. pipe write end) created that way clear the inherit flag. */ for (i = 0; i < n_inherit_handles; i++) { SetHandleInformation(inherit_handles[i], HANDLE_FLAG_INHERIT, 0); } if (cp_res) { win32_kill_child_on_exit(process_information->hProcess); ResumeThread(process_information->hThread); } // XXX Else try again if CREATE_BREAKAWAY_FROM_JOB and GetLastError() == ERROR_ACCESS_DENIED? if (attribute_list) { DeleteProcThreadAttributeList(attribute_list); g_free(attribute_list); } g_free(wappname); g_free(wcommandline); g_free(wcurrentdirectory); return cp_res; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * 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: */
C/C++
wireshark/wsutil/win32-utils.h
/* win32-utils.h * Windows utility definitions * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2006 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WIN32UTIL_H__ #define __WIN32UTIL_H__ #include <wireshark.h> #include <windows.h> /** * @file * Unicode convenience routines. */ #ifdef __cplusplus extern "C" { #endif /** Quote the argument element if necessary, so that it will get * reconstructed correctly in the C runtime startup code. Note that * the unquoting algorithm in the C runtime is really weird, and * rather different than what Unix shells do. See stdargv.c in the C * runtime sources (in the Platform SDK, in src/crt). * * Stolen from GLib's protect_argv(), an internal routine that quotes * string in an argument list so that they arguments will be handled * correctly in the command-line string passed to CreateProcess() * if that string is constructed by gluing those strings together. * * @param argv The string to be quoted. May be NULL. * @return The string quoted to be used by CreateProcess */ WS_DLL_PUBLIC gchar * protect_arg (const gchar *argv); /** Generate a string for a Windows error. * * @param error The Windows error code * @return a localized UTF-8 string containing the corresponding error message */ WS_DLL_PUBLIC const char * win32strerror(DWORD error); /** Generate a string for a Win32 exception code. * * @param exception The exception code * @return a non-localized string containing the error message */ WS_DLL_PUBLIC const char * win32strexception(DWORD exception); /** * @brief ws_pipe_create_process Create a process and assign it to the main application * job object so that it will be killed when the main application exits. * * In order to limit unwanted handle duplicates in subprocesses all handles should be * created as not inheritable and passed in the inherit_handles array. This function * marks the handles as inheritable for as short time as possible. Note that handles * passed to this function will have the inheritable flag cleared on exit. Processes * created with this function inherit only the provided handles. * * @param application_name Application name. Will be converted to its UTF-16 equivalent or NULL. * @param command_line Command line. Will be converted to its UTF-16 equivalent. * @param process_attributes Same as CreateProcess. * @param thread_attributes Same as CreateProcess. * @param n_inherit_handles Number of handles the child process will inherit. * @param inherit_handles Handles the child process will inherit. * @param creation_flags Will be ORed with CREATE_SUSPENDED|CREATE_BREAKAWAY_FROM_JOB. * @param environment Same as CreateProcess. * @param current_directory Current directory. Will be converted to its UTF-16 equivalent or NULL. * @param startup_info Same as CreateProcess. * @param process_information Same as CreateProcess. * @return */ WS_DLL_PUBLIC BOOL win32_create_process(const char *application_name, const char *command_line, LPSECURITY_ATTRIBUTES process_attributes, LPSECURITY_ATTRIBUTES thread_attributes, size_t n_inherit_handles, HANDLE *inherit_handles, DWORD creation_flags, LPVOID environment, const char *current_directory, LPSTARTUPINFO startup_info, LPPROCESS_INFORMATION process_information ); #ifdef __cplusplus } #endif #endif /* __WIN32UTIL_H__ */
C
wireshark/wsutil/wsgcrypt.c
/* wsgcrypt.c * Helper functions for libgcrypt * By Erik de Jong <[email protected]> * Copyright 2017 Erik de Jong * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "wsgcrypt.h" gcry_error_t ws_hmac_buffer(int algo, void *digest, const void *buffer, size_t length, const void *key, size_t keylen) { gcry_md_hd_t hmac_handle; gcry_error_t result = gcry_md_open(&hmac_handle, algo, GCRY_MD_FLAG_HMAC); if (result) { return result; } result = gcry_md_setkey(hmac_handle, key, keylen); if (result) { gcry_md_close(hmac_handle); return result; } gcry_md_write(hmac_handle, buffer, length); memcpy(digest, gcry_md_read(hmac_handle, 0), gcry_md_get_algo_dlen(algo)); gcry_md_close(hmac_handle); return GPG_ERR_NO_ERROR; } gcry_error_t ws_cmac_buffer(int algo, void *digest, const void *buffer, size_t length, const void *key, size_t keylen) { gcry_mac_hd_t cmac_handle; gcry_error_t result = gcry_mac_open(&cmac_handle, algo, 0, NULL); if (result) { return result; } result = gcry_mac_setkey(cmac_handle, key, keylen); if (result) { gcry_mac_close(cmac_handle); return result; } gcry_mac_write(cmac_handle, buffer, length); result = gcry_mac_read(cmac_handle, digest, &keylen); gcry_mac_close(cmac_handle); return result; } void crypt_des_ecb(guint8 *output, const guint8 *buffer, const guint8 *key56) { guint8 key64[8]; gcry_cipher_hd_t handle; memset(output, 0x00, 8); /* Transform 56 bits key into 64 bits DES key */ key64[0] = key56[0]; key64[1] = (key56[0] << 7) | (key56[1] >> 1); key64[2] = (key56[1] << 6) | (key56[2] >> 2); key64[3] = (key56[2] << 5) | (key56[3] >> 3); key64[4] = (key56[3] << 4) | (key56[4] >> 4); key64[5] = (key56[4] << 3) | (key56[5] >> 5); key64[6] = (key56[5] << 2) | (key56[6] >> 6); key64[7] = (key56[6] << 1); if (gcry_cipher_open(&handle, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0)) { return; } if (gcry_cipher_setkey(handle, key64, 8)) { gcry_cipher_close(handle); return; } gcry_cipher_encrypt(handle, output, 8, buffer, 8); gcry_cipher_close(handle); } size_t rsa_decrypt_inplace(const guint len, guchar* data, gcry_sexp_t pk, gboolean pkcs1_padding, char **err) { gint rc = 0; size_t decr_len = 0, i = 0; gcry_sexp_t s_data = NULL, s_plain = NULL; gcry_mpi_t encr_mpi = NULL, text = NULL; *err = NULL; /* create mpi representation of encrypted data */ rc = gcry_mpi_scan(&encr_mpi, GCRYMPI_FMT_USG, data, len, NULL); if (rc != 0 ) { *err = ws_strdup_printf("can't convert data to mpi (size %d):%s", len, gcry_strerror(rc)); return 0; } /* put the data into a simple list */ rc = gcry_sexp_build(&s_data, NULL, "(enc-val(rsa(a%m)))", encr_mpi); if (rc != 0) { *err = ws_strdup_printf("can't build encr_sexp:%s", gcry_strerror(rc)); decr_len = 0; goto out; } /* pass it to libgcrypt */ rc = gcry_pk_decrypt(&s_plain, s_data, pk); if (rc != 0) { *err = ws_strdup_printf("can't decrypt key:%s", gcry_strerror(rc)); decr_len = 0; goto out; } /* convert plain text sexp to mpi format */ text = gcry_sexp_nth_mpi(s_plain, 0, 0); if (! text) { *err = g_strdup("can't convert sexp to mpi"); decr_len = 0; goto out; } /* compute size requested for plaintext buffer */ rc = gcry_mpi_print(GCRYMPI_FMT_USG, NULL, 0, &decr_len, text); if (rc != 0) { *err = ws_strdup_printf("can't compute decr size:%s", gcry_strerror(rc)); decr_len = 0; goto out; } /* sanity check on out buffer */ if (decr_len > len) { *err = ws_strdup_printf("decrypted data is too long ?!? (%zu max %d)", decr_len, len); decr_len = 0; goto out; } /* write plain text to newly allocated buffer */ rc = gcry_mpi_print(GCRYMPI_FMT_USG, data, len, &decr_len, text); if (rc != 0) { *err = ws_strdup_printf("can't print decr data to mpi (size %zu):%s", decr_len, gcry_strerror(rc)); decr_len = 0; goto out; } if (pkcs1_padding) { /* strip the padding*/ rc = 0; for (i = 1; i < decr_len; i++) { if (data[i] == 0) { rc = (gint) i+1; break; } } decr_len -= rc; memmove(data, data+rc, decr_len); } out: gcry_sexp_release(s_data); gcry_sexp_release(s_plain); gcry_mpi_release(encr_mpi); gcry_mpi_release(text); return decr_len; } gcry_error_t hkdf_expand(int hashalgo, const guint8 *prk, guint prk_len, const guint8 *info, guint info_len, guint8 *out, guint out_len) { // Current maximum hash output size: 48 bytes for SHA-384. guchar lastoutput[48]; gcry_md_hd_t h; gcry_error_t err; const guint hash_len = gcry_md_get_algo_dlen(hashalgo); /* Some sanity checks */ if (!(out_len > 0 && out_len <= 255 * hash_len) || !(hash_len > 0 && hash_len <= sizeof(lastoutput))) { return GPG_ERR_INV_ARG; } err = gcry_md_open(&h, hashalgo, GCRY_MD_FLAG_HMAC); if (err) { return err; } for (guint offset = 0; offset < out_len; offset += hash_len) { gcry_md_reset(h); gcry_md_setkey(h, prk, prk_len); /* Set PRK */ if (offset > 0) { gcry_md_write(h, lastoutput, hash_len); /* T(1..N) */ } gcry_md_write(h, info, info_len); /* info */ gcry_md_putc(h, (guint8) (offset / hash_len + 1)); /* constant 0x01..N */ memcpy(lastoutput, gcry_md_read(h, hashalgo), hash_len); memcpy(out + offset, lastoutput, MIN(hash_len, out_len - offset)); } gcry_md_close(h); return 0; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/wsgcrypt.h
/** @file * * Wrapper around libgcrypt's include file gcrypt.h. * For libgcrypt 1.5.0, including gcrypt.h directly brings up lots of * compiler warnings about deprecated definitions. * Try to work around these warnings to ensure a clean build with -Werror. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 2007 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WSGCRYPT_H__ #define __WSGCRYPT_H__ #include <wireshark.h> #include <gcrypt.h> #define HASH_MD5_LENGTH 16 #define HASH_SHA1_LENGTH 20 #define HASH_SHA2_224_LENGTH 28 #define HASH_SHA2_256_LENGTH 32 #define HASH_SHA2_384_LENGTH 48 #define HASH_SHA2_512_LENGTH 64 /* Convenience function to calculate the HMAC from the data in BUFFER of size LENGTH with key KEY of size KEYLEN using the algorithm ALGO avoiding the creating of a hash object. The hash is returned in the caller provided buffer DIGEST which must be large enough to hold the digest of the given algorithm. */ WS_DLL_PUBLIC gcry_error_t ws_hmac_buffer(int algo, void *digest, const void *buffer, size_t length, const void *key, size_t keylen); WS_DLL_PUBLIC gcry_error_t ws_cmac_buffer(int algo, void *digest, const void *buffer, size_t length, const void *key, size_t keylen); /* Convenience function to encrypt 8 bytes in BUFFER with DES using the 56 bits KEY expanded to 64 bits as key, encrypted data is returned in OUTPUT which must be at least 8 bytes large */ WS_DLL_PUBLIC void crypt_des_ecb(guint8 *output, const guint8 *buffer, const guint8 *key56); /* Convenience function for RSA decryption. Returns decrypted length on success, 0 on failure */ WS_DLL_PUBLIC size_t rsa_decrypt_inplace(const guint len, guchar* data, gcry_sexp_t pk, gboolean pkcs1_padding, char **err); /** * RFC 5869 HMAC-based Extract-and-Expand Key Derivation Function (HKDF): * HKDF-Expand(PRK, info, L) -> OKM * * @param hashalgo [in] Libgcrypt hash algorithm identifier. * @param prk [in] Pseudo-random key. * @param prk_len [in] Length of prk. * @param info [in] Optional context (can be NULL if info_len is zero). * @param info_len [in] Length of info. * @param out [out] Output keying material. * @param out_len [in] Size of output keying material. * @return 0 on success and an error code otherwise. */ WS_DLL_PUBLIC gcry_error_t hkdf_expand(int hashalgo, const guint8 *prk, guint prk_len, const guint8 *info, guint info_len, guint8 *out, guint out_len); /* * Calculate HKDF-Extract(salt, IKM) -> PRK according to RFC 5869. * Caller MUST ensure that 'prk' is large enough to store the digest from hash * algorithm 'hashalgo' (e.g. 32 bytes for SHA-256). */ static inline gcry_error_t hkdf_extract(int hashalgo, const guint8 *salt, size_t salt_len, const guint8 *ikm, size_t ikm_len, guint8 *prk) { /* PRK = HMAC-Hash(salt, IKM) where salt is key, and IKM is input. */ return ws_hmac_buffer(hashalgo, prk, ikm, ikm_len, salt, salt_len); } #endif /* __WSGCRYPT_H__ */
C
wireshark/wsutil/wsjson.c
/* wsjson.c * JSON parsing functions. * * Copyright 2016, Dario Lombardo * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN #include "wsjson.h" #include <string.h> #include <errno.h> #include <wsutil/jsmn.h> #include <wsutil/str_util.h> #include <wsutil/unicode-utils.h> #include <wsutil/wslog.h> gboolean json_validate(const guint8 *buf, const size_t len) { gboolean ret = TRUE; /* We expect no more than 1024 tokens */ guint max_tokens = 1024; jsmntok_t* t; jsmn_parser p; int rcode; /* * Make sure the buffer isn't empty and the first octet isn't a NUL; * otherwise, the parser will immediately stop parsing and not validate * anything after that, so it'll just think it was handed an empty string. * * XXX - should we check for NULs anywhere in the buffer? */ if (len == 0) { ws_debug("JSON string is empty"); return FALSE; } if (buf[0] == '\0') { ws_debug("invalid character inside JSON string"); return FALSE; } t = g_new0(jsmntok_t, max_tokens); if (!t) return FALSE; jsmn_init(&p); rcode = jsmn_parse(&p, buf, len, t, max_tokens); if (rcode < 0) { switch (rcode) { case JSMN_ERROR_NOMEM: ws_debug("not enough tokens were provided"); break; case JSMN_ERROR_INVAL: ws_debug("invalid character inside JSON string"); break; case JSMN_ERROR_PART: ws_debug("the string is not a full JSON packet, " "more bytes expected"); break; default: ws_debug("unexpected error"); break; } ret = FALSE; } g_free(t); return ret; } int json_parse(const char *buf, jsmntok_t *tokens, unsigned int max_tokens) { jsmn_parser p; jsmn_init(&p); return jsmn_parse(&p, buf, strlen(buf), tokens, max_tokens); } static jsmntok_t *json_get_next_object(jsmntok_t *cur) { int i; jsmntok_t *next = cur+1; for (i = 0; i < cur->size; i++) { next = json_get_next_object(next); } return next; } jsmntok_t *json_get_object(const char *buf, jsmntok_t *parent, const char *name) { int i; jsmntok_t *cur = parent+1; for (i = 0; i < parent->size; i++) { if (cur->type == JSMN_STRING && !strncmp(&buf[cur->start], name, cur->end - cur->start) && strlen(name) == (size_t)(cur->end - cur->start) && cur->size == 1 && (cur+1)->type == JSMN_OBJECT) { return cur+1; } cur = json_get_next_object(cur); } return NULL; } jsmntok_t *json_get_array(const char *buf, jsmntok_t *parent, const char *name) { int i; jsmntok_t *cur = parent+1; for (i = 0; i < parent->size; i++) { if (cur->type == JSMN_STRING && !strncmp(&buf[cur->start], name, cur->end - cur->start) && strlen(name) == (size_t)(cur->end - cur->start) && cur->size == 1 && (cur+1)->type == JSMN_ARRAY) { return cur+1; } cur = json_get_next_object(cur); } return NULL; } int json_get_array_len(jsmntok_t *array) { if (array->type != JSMN_ARRAY) return -1; return array->size; } jsmntok_t *json_get_array_index(jsmntok_t *array, int idx) { int i; jsmntok_t *cur = array+1; if (array->type != JSMN_ARRAY || idx < 0 || idx >= array->size) return NULL; for (i = 0; i < idx; i++) cur = json_get_next_object(cur); return cur; } char *json_get_string(char *buf, jsmntok_t *parent, const char *name) { int i; jsmntok_t *cur = parent+1; for (i = 0; i < parent->size; i++) { if (cur->type == JSMN_STRING && !strncmp(&buf[cur->start], name, cur->end - cur->start) && strlen(name) == (size_t)(cur->end - cur->start) && cur->size == 1 && (cur+1)->type == JSMN_STRING) { buf[(cur+1)->end] = '\0'; if (!json_decode_string_inplace(&buf[(cur+1)->start])) return NULL; return &buf[(cur+1)->start]; } cur = json_get_next_object(cur); } return NULL; } gboolean json_get_double(char *buf, jsmntok_t *parent, const char *name, gdouble *val) { int i; jsmntok_t *cur = parent+1; for (i = 0; i < parent->size; i++) { if (cur->type == JSMN_STRING && !strncmp(&buf[cur->start], name, cur->end - cur->start) && strlen(name) == (size_t)(cur->end - cur->start) && cur->size == 1 && (cur+1)->type == JSMN_PRIMITIVE) { buf[(cur+1)->end] = '\0'; *val = g_ascii_strtod(&buf[(cur+1)->start], NULL); if (errno != 0) return FALSE; return TRUE; } cur = json_get_next_object(cur); } return FALSE; } gboolean json_decode_string_inplace(char *text) { const char *input = text; char *output = text; while (*input) { char ch = *input++; if (ch == '\\') { ch = *input++; switch (ch) { case '\"': case '\\': case '/': *output++ = ch; break; case 'b': *output++ = '\b'; break; case 'f': *output++ = '\f'; break; case 'n': *output++ = '\n'; break; case 'r': *output++ = '\r'; break; case 't': *output++ = '\t'; break; case 'u': { guint32 unicode_hex = 0; int k; int bin; for (k = 0; k < 4; k++) { unicode_hex <<= 4; ch = *input++; bin = ws_xton(ch); if (bin == -1) return FALSE; unicode_hex |= bin; } if ((IS_LEAD_SURROGATE(unicode_hex))) { guint16 lead_surrogate = unicode_hex; guint16 trail_surrogate = 0; if (input[0] != '\\' || input[1] != 'u') return FALSE; input += 2; for (k = 0; k < 4; k++) { trail_surrogate <<= 4; ch = *input++; bin = ws_xton(ch); if (bin == -1) return FALSE; trail_surrogate |= bin; } if ((!IS_TRAIL_SURROGATE(trail_surrogate))) return FALSE; unicode_hex = SURROGATE_VALUE(lead_surrogate,trail_surrogate); } else if ((IS_TRAIL_SURROGATE(unicode_hex))) { return FALSE; } if (!g_unichar_validate(unicode_hex)) return FALSE; /* Don't allow NUL byte injection. */ if (unicode_hex == 0) return FALSE; /* \uXXXX => 6 bytes, and g_unichar_to_utf8() requires to have output buffer at least 6 bytes -> OK. */ k = g_unichar_to_utf8(unicode_hex, output); output += k; break; } default: return FALSE; } } else { *output = ch; output++; } } *output = '\0'; return TRUE; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/wsjson.h
/** @file * * JSON parsing functions. * * Copyright 2016, Dario Lombardo * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WSJSON_H__ #define __WSJSON_H__ #include "ws_symbol_export.h" #include <glib.h> #include "jsmn.h" #ifdef __cplusplus extern "C" { #endif /** * Check if a buffer is json an returns true if it is. */ WS_DLL_PUBLIC gboolean json_validate(const guint8 *buf, const size_t len); WS_DLL_PUBLIC int json_parse(const char *buf, jsmntok_t *tokens, unsigned int max_tokens); /** * Get the pointer to an object belonging to parent object and named as the name variable. * Returns NULL if not found. */ WS_DLL_PUBLIC jsmntok_t *json_get_object(const char *buf, jsmntok_t *parent, const char *name); /** * Get the pointer to an array belonging to parent object and named as the name variable. * Returns NULL if not found. */ WS_DLL_PUBLIC jsmntok_t *json_get_array(const char *buf, jsmntok_t *parent, const char *name); /** * Get the number of elements of an array. * Returns -1 if the JSON objecct is not an array. */ WS_DLL_PUBLIC int json_get_array_len(jsmntok_t *array); /** * Get the pointer to idx element of an array. * Returns NULL if not found. */ WS_DLL_PUBLIC jsmntok_t *json_get_array_index(jsmntok_t *parent, int idx); /** * Get the unescaped value of a string object belonging to parent object and named as the name variable. * Returns NULL if not found. Caution: it modifies input buffer. */ WS_DLL_PUBLIC char *json_get_string(char *buf, jsmntok_t *parent, const char *name); /** * Get the value of a number object belonging to parent object and named as the name variable. * Returns FALSE if not found. Caution: it modifies input buffer. * Scientific notation not supported yet. */ WS_DLL_PUBLIC gboolean json_get_double(char *buf, jsmntok_t *parent, const char *name, gdouble *val); /** * Decode the contents of a JSON string value by overwriting the input data. * Returns TRUE on success and FALSE if invalid characters were encountered. */ WS_DLL_PUBLIC gboolean json_decode_string_inplace(char *text); #ifdef __cplusplus } #endif #endif /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C
wireshark/wsutil/wslog.c
/* * Copyright 2021, João Valverde <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "wslog.h" #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> /* Because ws_assert() dependes on ws_error() we do not use it * here and fall back on assert() instead. */ #include <assert.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef _WIN32 #include <process.h> #include <windows.h> #include <conio.h> #endif #include "file_util.h" #include "time_util.h" #include "to_str.h" #include "strtoi.h" #ifdef _WIN32 #include "console_win32.h" #endif #define ASSERT(expr) assert(expr) /* Runtime log level. */ #define ENV_VAR_LEVEL "WIRESHARK_LOG_LEVEL" /* Log domains enabled/disabled. */ #define ENV_VAR_DOMAIN "WIRESHARK_LOG_DOMAIN" /* Alias "domain" and "domains". */ #define ENV_VAR_DOMAIN_S "WIRESHARK_LOG_DOMAINS" /* Log level that generates a trap and aborts. Can be "critical" * or "warning". */ #define ENV_VAR_FATAL "WIRESHARK_LOG_FATAL" /* Log domains that are fatal. */ #define ENV_VAR_FATAL_DOMAIN "WIRESHARK_LOG_FATAL_DOMAIN" /* Alias "domain" and "domains". */ #define ENV_VAR_FATAL_DOMAIN_S "WIRESHARK_LOG_FATAL_DOMAINS" /* Domains that will produce debug output, regardless of log level or * domain filter. */ #define ENV_VAR_DEBUG "WIRESHARK_LOG_DEBUG" /* Domains that will produce noisy output, regardless of log level or * domain filter. */ #define ENV_VAR_NOISY "WIRESHARK_LOG_NOISY" #define DEFAULT_LOG_LEVEL LOG_LEVEL_MESSAGE #define DEFAULT_PROGNAME "PID" #define DOMAIN_UNDEFED(domain) ((domain) == NULL || *(domain) == '\0') #define DOMAIN_DEFINED(domain) (!DOMAIN_UNDEFED(domain)) /* * Note: I didn't measure it but I assume using a string array is faster than * a GHashTable for small number N of domains. */ typedef struct { char **domainv; bool positive; /* positive or negative match */ enum ws_log_level min_level; /* for level filters */ } log_filter_t; /* If the module is not initialized by calling ws_log_init() all messages * will be printed regardless of log level. This is a feature, not a bug. */ static enum ws_log_level current_log_level = LOG_LEVEL_NONE; static bool stdout_color_enabled = false; static bool stderr_color_enabled = false; /* Use stdout for levels "info" and below, for backward compatibility * with GLib. */ static bool stdout_logging_enabled = false; static const char *registered_progname = DEFAULT_PROGNAME; /* List of domains to filter. */ static log_filter_t *domain_filter = NULL; /* List of domains to output debug level unconditionally. */ static log_filter_t *debug_filter = NULL; /* List of domains to output noisy level unconditionally. */ static log_filter_t *noisy_filter = NULL; /* List of domains that are fatal. */ static log_filter_t *fatal_filter = NULL; static ws_log_writer_cb *registered_log_writer = NULL; static void *registered_log_writer_data = NULL; static ws_log_writer_free_data_cb *registered_log_writer_data_free = NULL; static FILE *custom_log = NULL; static enum ws_log_level fatal_log_level = LOG_LEVEL_ERROR; static bool init_complete = false; ws_log_console_open_pref ws_log_console_open = LOG_CONSOLE_OPEN_NEVER; static void print_err(void (*vcmdarg_err)(const char *, va_list ap), int exit_failure, const char *fmt, ...) G_GNUC_PRINTF(3,4); static void ws_log_cleanup(void); const char *ws_log_level_to_string(enum ws_log_level level) { switch (level) { case LOG_LEVEL_NONE: return "(zero)"; case LOG_LEVEL_ECHO: return "ECHO"; case LOG_LEVEL_ERROR: return "ERROR"; case LOG_LEVEL_CRITICAL: return "CRITICAL"; case LOG_LEVEL_WARNING: return "WARNING"; case LOG_LEVEL_MESSAGE: return "MESSAGE"; case LOG_LEVEL_INFO: return "INFO"; case LOG_LEVEL_DEBUG: return "DEBUG"; case LOG_LEVEL_NOISY: return "NOISY"; default: return "(BOGUS LOG LEVEL)"; } } static enum ws_log_level string_to_log_level(const char *str_level) { if (!str_level) return LOG_LEVEL_NONE; if (g_ascii_strcasecmp(str_level, "noisy") == 0) return LOG_LEVEL_NOISY; else if (g_ascii_strcasecmp(str_level, "debug") == 0) return LOG_LEVEL_DEBUG; else if (g_ascii_strcasecmp(str_level, "info") == 0) return LOG_LEVEL_INFO; else if (g_ascii_strcasecmp(str_level, "message") == 0) return LOG_LEVEL_MESSAGE; else if (g_ascii_strcasecmp(str_level, "warning") == 0) return LOG_LEVEL_WARNING; else if (g_ascii_strcasecmp(str_level, "critical") == 0) return LOG_LEVEL_CRITICAL; else if (g_ascii_strcasecmp(str_level, "error") == 0) return LOG_LEVEL_ERROR; else if (g_ascii_strcasecmp(str_level, "echo") == 0) return LOG_LEVEL_ECHO; else return LOG_LEVEL_NONE; } WS_RETNONNULL static inline const char *domain_to_string(const char *domain) { return DOMAIN_UNDEFED(domain) ? "(none)" : domain; } static inline bool filter_contains(log_filter_t *filter, const char *domain) { if (filter == NULL || DOMAIN_UNDEFED(domain)) return false; for (char **domv = filter->domainv; *domv != NULL; domv++) { if (g_ascii_strcasecmp(*domv, domain) == 0) { return true; } } return false; } static inline bool level_filter_matches(log_filter_t *filter, const char *domain, enum ws_log_level level, bool *active_ptr) { if (filter == NULL || DOMAIN_UNDEFED(domain)) return false; if (!filter_contains(filter, domain)) return false; if (filter->positive) { if (active_ptr) *active_ptr = level >= filter->min_level; return true; } /* negative match */ if (level <= filter->min_level) { if (active_ptr) *active_ptr = false; return true; } return false; } bool ws_log_msg_is_active(const char *domain, enum ws_log_level level) { /* * Higher numerical levels have higher priority. Critical and above * are always enabled. */ if (level >= LOG_LEVEL_CRITICAL) return true; /* * Check if the level has been configured as fatal. */ if (level >= fatal_log_level) return true; /* * Check if the domain has been configured as fatal. */ if (DOMAIN_DEFINED(domain) && fatal_filter != NULL) { if (filter_contains(fatal_filter, domain) && fatal_filter->positive) { return true; } } /* * The debug/noisy filter overrides the other parameters. */ if (DOMAIN_DEFINED(domain)) { bool active; if (level_filter_matches(noisy_filter, domain, level, &active)) return active; if (level_filter_matches(debug_filter, domain, level, &active)) return active; } /* * If the priority is lower than the current minimum drop the * message. */ if (level < current_log_level) return false; /* * If we don't have domain filtering enabled we are done. */ if (domain_filter == NULL) return true; /* * We have a filter but we don't use it with the undefined domain, * pretty much every permanent call to ws_log should be using a * chosen domain. */ if (DOMAIN_UNDEFED(domain)) return true; /* Check if the domain filter matches. */ if (filter_contains(domain_filter, domain)) return domain_filter->positive; /* We have a domain filter but it didn't match. */ return !domain_filter->positive; } enum ws_log_level ws_log_get_level(void) { return current_log_level; } enum ws_log_level ws_log_set_level(enum ws_log_level level) { if (level <= LOG_LEVEL_NONE || level >= _LOG_LEVEL_LAST) return LOG_LEVEL_NONE; if (level > LOG_LEVEL_CRITICAL) level = LOG_LEVEL_CRITICAL; current_log_level = level; return current_log_level; } enum ws_log_level ws_log_set_level_str(const char *str_level) { enum ws_log_level level; level = string_to_log_level(str_level); return ws_log_set_level(level); } static const char *opt_level = "--log-level"; static const char *opt_domain = "--log-domain"; /* Alias "domain" and "domains". */ static const char *opt_domain_s = "--log-domains"; static const char *opt_file = "--log-file"; static const char *opt_fatal = "--log-fatal"; static const char *opt_fatal_domain = "--log-fatal-domain"; /* Alias "domain" and "domains". */ static const char *opt_fatal_domain_s = "--log-fatal-domains"; static const char *opt_debug = "--log-debug"; static const char *opt_noisy = "--log-noisy"; static void print_err(void (*vcmdarg_err)(const char *, va_list ap), int exit_failure, const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (vcmdarg_err) vcmdarg_err(fmt, ap); else vfprintf(stderr, fmt, ap); va_end(ap); if (exit_failure != LOG_ARGS_NOEXIT) exit(exit_failure); } /* * This tries to convert old log level preference to a wslog * configuration. The string must start with "console.log.level:" * It receives an argv for { '-o', 'console.log.level:nnn', ...} or * { '-oconsole.log.level:nnn', ...}. */ static void parse_console_compat_option(char *argv[], void (*vcmdarg_err)(const char *, va_list ap), int exit_failure) { const char *mask_str; uint32_t mask; enum ws_log_level level; ASSERT(argv != NULL); if (argv[0] == NULL) return; if (strcmp(argv[0], "-o") == 0) { if (argv[1] == NULL || !g_str_has_prefix(argv[1], "console.log.level:")) { /* Not what we were looking for. */ return; } mask_str = argv[1] + strlen("console.log.level:"); } else if (g_str_has_prefix(argv[0], "-oconsole.log.level:")) { mask_str = argv[0] + strlen("-oconsole.log.level:"); } else { /* Not what we were looking for. */ return; } print_err(vcmdarg_err, LOG_ARGS_NOEXIT, "Option 'console.log.level' is deprecated, consult '--help' " "for diagnostic message options."); if (*mask_str == '\0') { print_err(vcmdarg_err, exit_failure, "Missing value to 'console.log.level' option."); return; } if (!ws_basestrtou32(mask_str, NULL, &mask, 10)) { print_err(vcmdarg_err, exit_failure, "%s is not a valid decimal number.", mask_str); return; } /* * The lowest priority bit in the mask defines the level. */ if (mask & G_LOG_LEVEL_DEBUG) level = LOG_LEVEL_DEBUG; else if (mask & G_LOG_LEVEL_INFO) level = LOG_LEVEL_INFO; else if (mask & G_LOG_LEVEL_MESSAGE) level = LOG_LEVEL_MESSAGE; else if (mask & G_LOG_LEVEL_WARNING) level = LOG_LEVEL_WARNING; else if (mask & G_LOG_LEVEL_CRITICAL) level = LOG_LEVEL_CRITICAL; else if (mask & G_LOG_LEVEL_ERROR) level = LOG_LEVEL_ERROR; else level = LOG_LEVEL_NONE; if (level == LOG_LEVEL_NONE) { /* Some values (like zero) might not contain any meaningful bits. * Throwing an error in that case seems appropriate. */ print_err(vcmdarg_err, exit_failure, "Value %s is not a valid log mask.", mask_str); return; } ws_log_set_level(level); } /* Match "arg_name=value" or "arg_name value" to opt_name. */ static bool optequal(const char *arg, const char *opt) { ASSERT(arg); ASSERT(opt); #define ARGEND(arg) (*(arg) == '\0' || *(arg) == ' ' || *(arg) == '=') while (!ARGEND(arg) && *opt != '\0') { if (*arg != *opt) { return false; } arg += 1; opt += 1; } if (ARGEND(arg) && *opt == '\0') { return true; } return false; } int ws_log_parse_args(int *argc_ptr, char *argv[], void (*vcmdarg_err)(const char *, va_list ap), int exit_failure) { char **ptr = argv; int count = *argc_ptr; int ret = 0; size_t optlen; const char *option, *value; int extra; if (argc_ptr == NULL || argv == NULL) return -1; /* Assert ws_log_init() was called before ws_log_parse_args(). */ ASSERT(init_complete); /* Configure from command line. */ while (*ptr != NULL) { if (optequal(*ptr, opt_level)) { option = opt_level; optlen = strlen(opt_level); } else if (optequal(*ptr, opt_domain)) { option = opt_domain; optlen = strlen(opt_domain); } else if (optequal(*ptr, opt_domain_s)) { option = opt_domain; /* Alias */ optlen = strlen(opt_domain_s); } else if (optequal(*ptr, opt_fatal_domain)) { option = opt_fatal_domain; optlen = strlen(opt_fatal_domain); } else if (optequal(*ptr, opt_fatal_domain_s)) { option = opt_fatal_domain; /* Alias */ optlen = strlen(opt_fatal_domain_s); } else if (optequal(*ptr, opt_file)) { option = opt_file; optlen = strlen(opt_file); } else if (optequal(*ptr, opt_fatal)) { option = opt_fatal; optlen = strlen(opt_fatal); } else if (optequal(*ptr, opt_debug)) { option = opt_debug; optlen = strlen(opt_debug); } else if (optequal(*ptr, opt_noisy)) { option = opt_noisy; optlen = strlen(opt_noisy); } else { /* Check is we have the old '-o console.log.level' flag, * or '-oconsole.log.level', for backward compatibility. * Then if we do ignore it after processing and let the * preferences module handle it later. */ if (*(*ptr + 0) == '-' && *(*ptr + 1) == 'o') { parse_console_compat_option(ptr, vcmdarg_err, exit_failure); } ptr += 1; count -= 1; continue; } value = *ptr + optlen; /* Two possibilities: * --<option> <value> * or * --<option>=<value> */ if (value[0] == '\0') { /* value is separated with blank space */ value = *(ptr + 1); extra = 1; if (value == NULL || !*value || *value == '-') { /* If the option value after the blank starts with '-' assume * it is another option. */ print_err(vcmdarg_err, exit_failure, "Option \"%s\" requires a value.\n", *ptr); option = NULL; extra = 0; ret += 1; } } else if (value[0] == '=') { /* value is after equals */ value += 1; extra = 0; } else { /* Option isn't known. */ ptr += 1; count -= 1; continue; } if (option == opt_level) { if (ws_log_set_level_str(value) == LOG_LEVEL_NONE) { print_err(vcmdarg_err, exit_failure, "Invalid log level \"%s\".\n", value); ret += 1; } } else if (option == opt_domain) { ws_log_set_domain_filter(value); } else if (option == opt_fatal_domain) { ws_log_set_fatal_domain_filter(value); } else if (value && option == opt_file) { FILE *fp = ws_fopen(value, "w"); if (fp == NULL) { print_err(vcmdarg_err, exit_failure, "Error opening file '%s' for writing: %s.\n", value, g_strerror(errno)); ret += 1; } else { ws_log_add_custom_file(fp); } } else if (option == opt_fatal) { if (ws_log_set_fatal_level_str(value) == LOG_LEVEL_NONE) { print_err(vcmdarg_err, exit_failure, "Fatal log level must be \"critical\" or " "\"warning\", not \"%s\".\n", value); ret += 1; } } else if (option == opt_debug) { ws_log_set_debug_filter(value); } else if (option == opt_noisy) { ws_log_set_noisy_filter(value); } else { /* Option value missing or invalid, do nothing. */ } /* * We found a log option. We will remove it from * the argv by moving up the other strings in the array. This is * so that it doesn't generate an unrecognized option * error further along in the initialization process. */ /* Include the terminating NULL in the memmove. */ memmove(ptr, ptr + 1 + extra, (count - extra) * sizeof(*ptr)); /* No need to increment ptr here. */ count -= (1 + extra); *argc_ptr -= (1 + extra); } return ret; } static void free_log_filter(log_filter_t **filter_ptr) { if (filter_ptr == NULL || *filter_ptr == NULL) return; g_strfreev((*filter_ptr)->domainv); g_free(*filter_ptr); *filter_ptr = NULL; } static void tokenize_filter_str(log_filter_t **filter_ptr, const char *str_filter, enum ws_log_level min_level) { const char *sep = ",;"; bool negated = false; log_filter_t *filter; ASSERT(filter_ptr); ASSERT(*filter_ptr == NULL); if (str_filter == NULL) return; if (str_filter[0] == '!') { negated = true; str_filter += 1; } if (*str_filter == '\0') return; filter = g_new(log_filter_t, 1); filter->domainv = g_strsplit_set(str_filter, sep, -1); filter->positive = !negated; filter->min_level = min_level; *filter_ptr = filter; } void ws_log_set_domain_filter(const char *str_filter) { free_log_filter(&domain_filter); tokenize_filter_str(&domain_filter, str_filter, LOG_LEVEL_NONE); } void ws_log_set_fatal_domain_filter(const char *str_filter) { free_log_filter(&fatal_filter); tokenize_filter_str(&fatal_filter, str_filter, LOG_LEVEL_NONE); } void ws_log_set_debug_filter(const char *str_filter) { free_log_filter(&debug_filter); tokenize_filter_str(&debug_filter, str_filter, LOG_LEVEL_DEBUG); } void ws_log_set_noisy_filter(const char *str_filter) { free_log_filter(&noisy_filter); tokenize_filter_str(&noisy_filter, str_filter, LOG_LEVEL_NOISY); } enum ws_log_level ws_log_set_fatal_level(enum ws_log_level level) { if (level <= LOG_LEVEL_NONE || level >= _LOG_LEVEL_LAST) return LOG_LEVEL_NONE; if (level > LOG_LEVEL_ERROR) level = LOG_LEVEL_ERROR; if (level < LOG_LEVEL_WARNING) level = LOG_LEVEL_WARNING; fatal_log_level = level; return fatal_log_level; } enum ws_log_level ws_log_set_fatal_level_str(const char *str_level) { enum ws_log_level level; level = string_to_log_level(str_level); return ws_log_set_fatal_level(level); } void ws_log_set_writer(ws_log_writer_cb *writer) { if (registered_log_writer_data_free) registered_log_writer_data_free(registered_log_writer_data); registered_log_writer = writer; registered_log_writer_data = NULL; registered_log_writer_data_free = NULL; } void ws_log_set_writer_with_data(ws_log_writer_cb *writer, void *user_data, ws_log_writer_free_data_cb *free_user_data) { if (registered_log_writer_data_free) registered_log_writer_data_free(registered_log_writer_data); registered_log_writer = writer; registered_log_writer_data = user_data; registered_log_writer_data_free = free_user_data; } static void glib_log_handler(const char *domain, GLogLevelFlags flags, const char *message, gpointer user_data _U_) { enum ws_log_level level; /* * The highest priority bit in the mask defines the level. We * ignore the GLib fatal log level mask and use our own fatal * log level setting instead. */ if (flags & G_LOG_LEVEL_ERROR) level = LOG_LEVEL_ERROR; else if (flags & G_LOG_LEVEL_CRITICAL) level = LOG_LEVEL_CRITICAL; else if (flags & G_LOG_LEVEL_WARNING) level = LOG_LEVEL_WARNING; else if (flags & G_LOG_LEVEL_MESSAGE) level = LOG_LEVEL_MESSAGE; else if (flags & G_LOG_LEVEL_INFO) level = LOG_LEVEL_INFO; else if (flags & G_LOG_LEVEL_DEBUG) level = LOG_LEVEL_DEBUG; else level = LOG_LEVEL_NONE; /* Should not happen. */ ws_log(domain, level, "%s", message); } #ifdef _WIN32 static void load_registry(void) { LONG lResult; DWORD ptype; DWORD data; DWORD data_size = sizeof(DWORD); lResult = RegGetValueA(HKEY_CURRENT_USER, "Software\\Wireshark", LOG_HKCU_CONSOLE_OPEN, RRF_RT_REG_DWORD, &ptype, &data, &data_size); if (lResult != ERROR_SUCCESS || ptype != REG_DWORD) { return; } ws_log_console_open = (ws_log_console_open_pref)data; } #endif /* * We can't write to stderr in ws_log_init() because dumpcap uses stderr * to communicate with the parent and it will block. We have to use * vcmdarg_err to report errors. */ void ws_log_init(const char *progname, void (*vcmdarg_err)(const char *, va_list ap)) { const char *env; int fd; if (progname != NULL) { registered_progname = progname; g_set_prgname(progname); } current_log_level = DEFAULT_LOG_LEVEL; if ((fd = fileno(stdout)) >= 0) stdout_color_enabled = g_log_writer_supports_color(fd); if ((fd = fileno(stderr)) >= 0) stderr_color_enabled = g_log_writer_supports_color(fd); /* Set the GLib log handler for the default domain. */ g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL, glib_log_handler, NULL); /* Set the GLib log handler for GLib itself. */ g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL, glib_log_handler, NULL); #ifdef _WIN32 load_registry(); /* if the user wants a console to be always there, well, we should open one for him */ if (ws_log_console_open == LOG_CONSOLE_OPEN_ALWAYS) { create_console(); } #endif atexit(ws_log_cleanup); /* Configure from environment. */ env = g_getenv(ENV_VAR_LEVEL); if (env != NULL) { if (ws_log_set_level_str(env) == LOG_LEVEL_NONE) { print_err(vcmdarg_err, LOG_ARGS_NOEXIT, "Ignoring invalid environment value %s=\"%s\"", ENV_VAR_LEVEL, env); } } env = g_getenv(ENV_VAR_FATAL); if (env != NULL) { if (ws_log_set_fatal_level_str(env) == LOG_LEVEL_NONE) { print_err(vcmdarg_err, LOG_ARGS_NOEXIT, "Ignoring invalid environment value %s=\"%s\"", ENV_VAR_FATAL, env); } } /* Alias "domain" and "domains". The plural form wins. */ if ((env = g_getenv(ENV_VAR_DOMAIN_S)) != NULL) ws_log_set_domain_filter(env); else if ((env = g_getenv(ENV_VAR_DOMAIN)) != NULL) ws_log_set_domain_filter(env); /* Alias "domain" and "domains". The plural form wins. */ if ((env = g_getenv(ENV_VAR_FATAL_DOMAIN_S)) != NULL) ws_log_set_fatal_domain_filter(env); else if ((env = g_getenv(ENV_VAR_FATAL_DOMAIN)) != NULL) ws_log_set_fatal_domain_filter(env); env = g_getenv(ENV_VAR_DEBUG); if (env != NULL) ws_log_set_debug_filter(env); env = g_getenv(ENV_VAR_NOISY); if (env != NULL) ws_log_set_noisy_filter(env); init_complete = true; } void ws_log_init_with_writer(const char *progname, ws_log_writer_cb *writer, void (*vcmdarg_err)(const char *, va_list ap)) { registered_log_writer = writer; ws_log_init(progname, vcmdarg_err); } void ws_log_init_with_writer_and_data(const char *progname, ws_log_writer_cb *writer, void *user_data, ws_log_writer_free_data_cb *free_user_data, void (*vcmdarg_err)(const char *, va_list ap)) { registered_log_writer_data = user_data; registered_log_writer_data_free = free_user_data; ws_log_init_with_writer(progname, writer, vcmdarg_err); } #define MAGENTA "\033[35m" #define BLUE "\033[34m" #define CYAN "\033[36m" #define GREEN "\033[32m" #define YELLOW "\033[33m" #define RED "\033[31m" #define RESET "\033[0m" static inline const char *level_color_on(bool enable, enum ws_log_level level) { if (!enable) return ""; switch (level) { case LOG_LEVEL_NOISY: case LOG_LEVEL_DEBUG: return GREEN; case LOG_LEVEL_INFO: case LOG_LEVEL_MESSAGE: return CYAN; case LOG_LEVEL_WARNING: return YELLOW; case LOG_LEVEL_CRITICAL: return MAGENTA; case LOG_LEVEL_ERROR: return RED; case LOG_LEVEL_ECHO: return YELLOW; default: break; } return ""; } static inline const char *color_off(bool enable) { return enable ? RESET : ""; } #define NANOSECS_IN_MICROSEC 1000 /* * We must not call anything that might log a message * in the log handler context (GLib might log a message if we register * our own handler for the GLib domain). */ static void log_write_do_work(FILE *fp, bool use_color, struct tm *when, long nanosecs, intmax_t pid, const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *user_format, va_list user_ap) { if (!init_complete) fputs(" ** (noinit)", fp); /* Process */ fprintf(fp, " ** (%s:%"PRIdMAX") ", registered_progname, pid); /* Timestamp */ if (when != NULL && nanosecs >= 0) fprintf(fp, "%02d:%02d:%02d.%06ld ", when->tm_hour, when->tm_min, when->tm_sec, nanosecs / NANOSECS_IN_MICROSEC); else if (when != NULL) fprintf(fp, "%02d:%02d:%02d ", when->tm_hour, when->tm_min, when->tm_sec); else fputs("(notime) ", fp); /* Domain/level */ fprintf(fp, "[%s %s%s%s] ", domain_to_string(domain), level_color_on(use_color, level), ws_log_level_to_string(level), color_off(use_color)); /* File/line */ if (file != NULL && line >= 0) fprintf(fp, "%s:%ld ", file, line); else if (file != NULL) fprintf(fp, "%s ", file); /* Any formatting changes here need to be synced with ui/capture.c:capture_input_closed. */ fputs("-- ", fp); /* Function name */ if (func != NULL) fprintf(fp, "%s(): ", func); /* User message */ vfprintf(fp, user_format, user_ap); fputc('\n', fp); fflush(fp); } static inline struct tm *get_localtime(time_t unix_time, struct tm **cookie) { if (unix_time == (time_t)-1) return NULL; if (cookie && *cookie) return *cookie; struct tm *when = localtime(&unix_time); if (cookie) *cookie = when; return when; } static inline FILE *console_file(enum ws_log_level level) { if (level <= LOG_LEVEL_INFO && stdout_logging_enabled) return stdout; return stderr; } static inline bool console_color_enabled(enum ws_log_level level) { if (level <= LOG_LEVEL_INFO && stdout_logging_enabled) return stdout_color_enabled; return stderr_color_enabled; } static void log_write_fatal_msg(FILE *fp, intmax_t pid, const char *msg) { /* Process */ fprintf(fp, " ** (%s:%"PRIdMAX") %s", registered_progname, pid, msg); } /* * We must not call anything that might log a message * in the log handler context (GLib might log a message if we register * our own handler for the GLib domain). */ static void log_write_dispatch(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *user_format, va_list user_ap) { struct timespec tstamp; intmax_t pid; struct tm *cookie = NULL; bool fatal_event = false; const char *fatal_msg = NULL; if (level >= fatal_log_level && level != LOG_LEVEL_ECHO) { fatal_event = true; fatal_msg = "Aborting on fatal log level exception\n"; } else if (fatal_filter != NULL) { if (filter_contains(fatal_filter, domain) && fatal_filter->positive) { fatal_event = true; fatal_msg = "Aborting on fatal log domain exception\n"; } } ws_clock_get_realtime(&tstamp); pid = getpid(); #ifdef _WIN32 if (fatal_event || ws_log_console_open != LOG_CONSOLE_OPEN_NEVER) { /* the user wants a console or the application will terminate immediately */ create_console(); } #endif /* _WIN32 */ if (custom_log) { va_list user_ap_copy; va_copy(user_ap_copy, user_ap); log_write_do_work(custom_log, false, get_localtime(tstamp.tv_sec, &cookie), tstamp.tv_nsec, pid, domain, level, file, line, func, user_format, user_ap_copy); va_end(user_ap_copy); if (fatal_msg) { log_write_fatal_msg(custom_log, pid, fatal_msg); } } if (registered_log_writer) { registered_log_writer(domain, level, fatal_msg, tstamp, file, line, func, user_format, user_ap, registered_log_writer_data); } else { log_write_do_work(console_file(level), console_color_enabled(level), get_localtime(tstamp.tv_sec, &cookie), tstamp.tv_nsec, pid, domain, level, file, line, func, user_format, user_ap); if (fatal_msg) { log_write_fatal_msg(console_file(level), pid, fatal_msg); } } #ifdef _WIN32 if (fatal_event) { /* wait for a key press before the following error handler will terminate the program this way the user at least can read the error message */ printf("\n\nPress any key to exit\n"); _getch(); } #endif /* _WIN32 */ if (fatal_event) { abort(); } } void ws_logv(const char *domain, enum ws_log_level level, const char *format, va_list ap) { if (!ws_log_msg_is_active(domain, level)) return; log_write_dispatch(domain, level, NULL, -1, NULL, format, ap); } void ws_logv_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *format, va_list ap) { if (!ws_log_msg_is_active(domain, level)) return; log_write_dispatch(domain, level, file, line, func, format, ap); } void ws_log(const char *domain, enum ws_log_level level, const char *format, ...) { if (!ws_log_msg_is_active(domain, level)) return; va_list ap; va_start(ap, format); log_write_dispatch(domain, level, NULL, -1, NULL, format, ap); va_end(ap); } void ws_log_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *format, ...) { if (!ws_log_msg_is_active(domain, level)) return; va_list ap; va_start(ap, format); log_write_dispatch(domain, level, file, line, func, format, ap); va_end(ap); } void ws_log_fatal_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *format, ...) { va_list ap; va_start(ap, format); log_write_dispatch(domain, level, file, line, func, format, ap); va_end(ap); abort(); } void ws_log_write_always_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *format, ...) { va_list ap; va_start(ap, format); log_write_dispatch(domain, level, file, line, func, format, ap); va_end(ap); } static void append_trailer(const char *src, size_t src_length, wmem_strbuf_t *display, wmem_strbuf_t *underline) { gunichar ch; size_t hex_len; while (src_length > 0) { ch = g_utf8_get_char_validated(src, src_length); if (ch == (gunichar)-1 || ch == (gunichar)-2) { wmem_strbuf_append_hex(display, *src); wmem_strbuf_append_c_count(underline, '^', 4); src += 1; src_length -= 1; } else { if (g_unichar_isprint(ch)) { wmem_strbuf_append_unichar(display, ch); wmem_strbuf_append_c_count(underline, ' ', 1); } else { hex_len = wmem_strbuf_append_hex_unichar(display, ch); wmem_strbuf_append_c_count(underline, ' ', hex_len); } const char *tmp = g_utf8_next_char(src); src_length -= tmp - src; src = tmp; } } } static char * make_utf8_display(const char *src, size_t src_length, size_t good_length) { wmem_strbuf_t *display; wmem_strbuf_t *underline; gunichar ch; size_t hex_len; display = wmem_strbuf_create(NULL); underline = wmem_strbuf_create(NULL); for (const char *s = src; s < src + good_length; s = g_utf8_next_char(s)) { ch = g_utf8_get_char(s); if (g_unichar_isprint(ch)) { wmem_strbuf_append_unichar(display, ch); wmem_strbuf_append_c(underline, ' '); } else { hex_len = wmem_strbuf_append_hex_unichar(display, ch); wmem_strbuf_append_c_count(underline, ' ', hex_len); } } append_trailer(&src[good_length], src_length - good_length, display, underline); wmem_strbuf_append_c(display, '\n'); wmem_strbuf_append(display, underline->str); wmem_strbuf_destroy(underline); return wmem_strbuf_finalize(display); } void ws_log_utf8_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *string, ssize_t _length, const char *endptr) { if (!ws_log_msg_is_active(domain, level)) return; char *display; size_t length; size_t good_length; if (_length < 0) length = strlen(string); else length = _length; if (endptr == NULL || endptr < string) { /* Find the pointer to the first invalid byte. */ if (g_utf8_validate(string, length, &endptr)) { /* Valid string - should not happen. */ return; } } good_length = endptr - string; display = make_utf8_display(string, length, good_length); ws_log_write_always_full(domain, level, file, line, func, "Invalid UTF-8 at address %p offset %zu (length = %zu):\n%s", string, good_length, length, display); g_free(display); } void ws_log_buffer_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const uint8_t *ptr, size_t size, size_t max_bytes_len, const char *msg) { if (!ws_log_msg_is_active(domain, level)) return; char *bufstr = bytes_to_str_maxlen(NULL, ptr, size, max_bytes_len); if (G_UNLIKELY(msg == NULL)) ws_log_write_always_full(domain, level, file, line, func, "<buffer:%p>: %s (%zu bytes)", ptr, bufstr, size); else ws_log_write_always_full(domain, level, file, line, func, "%s: %s (%zu bytes)", msg, bufstr, size); wmem_free(NULL, bufstr); } void ws_log_file_writer(FILE *fp, const char *domain, enum ws_log_level level, struct timespec timestamp, intmax_t pid, const char *file, long line, const char *func, const char *user_format, va_list user_ap) { log_write_do_work(fp, false, get_localtime(timestamp.tv_sec, NULL), timestamp.tv_nsec, pid, domain, level, file, line, func, user_format, user_ap); } void ws_log_console_writer(const char *domain, enum ws_log_level level, struct timespec timestamp, intmax_t pid, const char *file, long line, const char *func, const char *user_format, va_list user_ap) { log_write_do_work(console_file(level), console_color_enabled(level), get_localtime(timestamp.tv_sec, NULL), timestamp.tv_nsec, pid, domain, level, file, line, func, user_format, user_ap); } WS_DLL_PUBLIC void ws_log_console_writer_set_use_stdout(bool use_stdout) { stdout_logging_enabled = use_stdout; } static void ws_log_cleanup(void) { if (registered_log_writer_data_free) { registered_log_writer_data_free(registered_log_writer_data); registered_log_writer_data = NULL; } if (custom_log) { fclose(custom_log); custom_log = NULL; } free_log_filter(&domain_filter); free_log_filter(&debug_filter); free_log_filter(&noisy_filter); free_log_filter(&fatal_filter); } void ws_log_add_custom_file(FILE *fp) { if (custom_log != NULL) { fclose(custom_log); } custom_log = fp; } #define USAGE_LEVEL \ "sets the active log level (\"critical\", \"warning\", etc.)" #define USAGE_FATAL \ "sets level to abort the program (\"critical\" or \"warning\")" #define USAGE_DOMAINS \ "comma-separated list of the active log domains" #define USAGE_FATAL_DOMAINS \ "list of domains that cause the program to abort" #define USAGE_DEBUG \ "list of domains with \"debug\" level" #define USAGE_NOISY \ "list of domains with \"noisy\" level" #define USAGE_FILE \ "file to output messages to (in addition to stderr)" void ws_log_print_usage(FILE *fp) { fprintf(fp, "Diagnostic output:\n"); fprintf(fp, " --log-level <level> " USAGE_LEVEL "\n"); fprintf(fp, " --log-fatal <level> " USAGE_FATAL "\n"); fprintf(fp, " --log-domains <[!]list> " USAGE_DOMAINS "\n"); fprintf(fp, " --log-fatal-domains <list>\n"); fprintf(fp, " " USAGE_FATAL_DOMAINS "\n"); fprintf(fp, " --log-debug <[!]list> " USAGE_DEBUG "\n"); fprintf(fp, " --log-noisy <[!]list> " USAGE_NOISY "\n"); fprintf(fp, " --log-file <path> " USAGE_FILE "\n"); }
C/C++
wireshark/wsutil/wslog.h
/** @file * * Copyright 2021, João Valverde <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WSLOG_H__ #define __WSLOG_H__ #include <inttypes.h> #include <stdbool.h> #include <stdio.h> #include <stdarg.h> #include <time.h> #include <glib.h> #include <ws_symbol_export.h> #include <ws_attributes.h> #include <ws_log_defs.h> #include <ws_posix_compat.h> #ifdef WS_LOG_DOMAIN #define _LOG_DOMAIN WS_LOG_DOMAIN #else #define _LOG_DOMAIN "" #endif #ifdef WS_DEBUG #define _LOG_DEBUG_ENABLED true #else #define _LOG_DEBUG_ENABLED false #endif /* * Define the macro WS_LOG_DOMAIN *before* including this header, * for example: * #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Console open preference is stored in the Windows registry. * HKEY_CURRENT_USER\Software\Wireshark\ConsoleOpen */ #define LOG_HKCU_CONSOLE_OPEN "ConsoleOpen" typedef enum { LOG_CONSOLE_OPEN_NEVER, LOG_CONSOLE_OPEN_AUTO, /* On demand. */ LOG_CONSOLE_OPEN_ALWAYS, /* Open during startup. */ } ws_log_console_open_pref; WSUTIL_EXPORT ws_log_console_open_pref ws_log_console_open; /** Callback for registering a log writer. */ typedef void (ws_log_writer_cb)(const char *domain, enum ws_log_level level, const char *fatal_msg, struct timespec timestamp, const char *file, long line, const char *func, const char *user_format, va_list user_ap, void *user_data); /** Callback for freeing a user data pointer. */ typedef void (ws_log_writer_free_data_cb)(void *user_data); WS_DLL_PUBLIC void ws_log_file_writer(FILE *fp, const char *domain, enum ws_log_level level, struct timespec timestamp, intmax_t pid, const char *file, long line, const char *func, const char *user_format, va_list user_ap); WS_DLL_PUBLIC void ws_log_console_writer(const char *domain, enum ws_log_level level, struct timespec timestamp, intmax_t pid, const char *file, long line, const char *func, const char *user_format, va_list user_ap); /** Configure log levels "info" and below to use stdout. * * Normally all log messages are written to stderr. For backward compatibility * with GLib calling this function with TRUE configures log levels "info", * "debug" and "noisy" to be written to stdout. */ WS_DLL_PUBLIC void ws_log_console_writer_set_use_stdout(bool use_stdout); /** Convert a numerical level to its string representation. */ WS_DLL_PUBLIC WS_RETNONNULL const char *ws_log_level_to_string(enum ws_log_level level); /** Checks if a domain and level combination generate output. * * Returns TRUE if a message will be printed for the domain/level combo. */ WS_DLL_PUBLIC bool ws_log_msg_is_active(const char *domain, enum ws_log_level level); /** Return the currently active log level. */ WS_DLL_PUBLIC enum ws_log_level ws_log_get_level(void); /** Set the active log level. Returns the active level or LOG_LEVEL_NONE * if level is invalid. */ WS_DLL_PUBLIC enum ws_log_level ws_log_set_level(enum ws_log_level level); /** Set the active log level from a string. * * String levels are "error", "critical", "warning", "message", "info", * "debug" and "noisy" (case insensitive). * Returns the new log level or LOG_LEVEL NONE if the string representation * is invalid. */ WS_DLL_PUBLIC enum ws_log_level ws_log_set_level_str(const char *str_level); /** Set a domain filter from a string. * * Domain filter is a case insensitive list separated by ',' or ';'. Only * the domains in the filter will generate output; the others will be muted. * Filter expressions can be preceded by '!' to invert the sense of the match. * In this case only non-matching domains will generate output. */ WS_DLL_PUBLIC void ws_log_set_domain_filter(const char *domain_filter); /** Set a fatal domain filter from a string. * * Domain filter is a case insensitive list separated by ',' or ';'. Domains * in the filter will cause the program to abort. */ WS_DLL_PUBLIC void ws_log_set_fatal_domain_filter(const char *domain_filter); /** Set a debug filter from a string. * * A debug filter lists all domains that should have debug level output turned * on, regardless of the global log level and domain filter. If negated * then debug (and below) will be disabled and the others unaffected by * the filter. */ WS_DLL_PUBLIC void ws_log_set_debug_filter(const char *str_filter); /** Set a noisy filter from a string. * * Same as ws_log_set_debug_filter() for "noisy" level. */ WS_DLL_PUBLIC void ws_log_set_noisy_filter(const char *str_filter); /** Set the fatal log level. * * Sets the log level at which calls to ws_log() will abort the program. The * argument can be LOG_LEVEL_ERROR, LOG_LEVEL_CRITICAL or LOG_LEVEL_WARNING. * Level LOG_LEVEL_ERROR is always fatal. */ WS_DLL_PUBLIC enum ws_log_level ws_log_set_fatal_level(enum ws_log_level level); /** Set the fatal log level from a string. * * Same as ws_log_set_fatal(), but accepts the strings "error", critical" or * "warning" instead as arguments. */ WS_DLL_PUBLIC enum ws_log_level ws_log_set_fatal_level_str(const char *str_level); /** Set the active log writer. * * The parameter 'writer' can be NULL to use the default writer. */ WS_DLL_PUBLIC void ws_log_set_writer(ws_log_writer_cb *writer); /** Set the active log writer. * * The parameter 'writer' can be NULL to use the default writer. * Accepts an extra user_data parameter that will be passed to * the log writer. */ WS_DLL_PUBLIC void ws_log_set_writer_with_data(ws_log_writer_cb *writer, void *user_data, ws_log_writer_free_data_cb *free_user_data); #define LOG_ARGS_NOEXIT -1 /** Parses the command line arguments for log options. * * Returns zero for no error, non-zero for one or more invalid options. */ WS_DLL_PUBLIC int ws_log_parse_args(int *argc_ptr, char *argv[], void (*vcmdarg_err)(const char *, va_list ap), int exit_failure); /** Initializes the logging code. * * Must be called at startup before using the log API. If provided * vcmdarg_err is used to print initialization errors. This usually means * a misconfigured environment variable. */ WS_DLL_PUBLIC void ws_log_init(const char *progname, void (*vcmdarg_err)(const char *, va_list ap)); /** Initializes the logging code. * * Can be used instead of wslog_init(). Takes an extra writer argument. * If provided this callback will be used instead of the default writer. */ WS_DLL_PUBLIC void ws_log_init_with_writer(const char *progname, ws_log_writer_cb *writer, void (*vcmdarg_err)(const char *, va_list ap)); /** Initializes the logging code. * * Accepts a user data pointer in addition to the writer. This pointer will * be provided to the writer with every invocation. If provided * free_user_data will be called during cleanup. */ WS_DLL_PUBLIC void ws_log_init_with_writer_and_data(const char *progname, ws_log_writer_cb *writer, void *user_data, ws_log_writer_free_data_cb *free_user_data, void (*vcmdarg_err)(const char *, va_list ap)); /** This function is called to output a message to the log. * * Takes a format string and a variable number of arguments. */ WS_DLL_PUBLIC void ws_log(const char *domain, enum ws_log_level level, const char *format, ...) G_GNUC_PRINTF(3,4); /** This function is called to output a message to the log. * * Takes a format string and a 'va_list'. */ WS_DLL_PUBLIC void ws_logv(const char *domain, enum ws_log_level level, const char *format, va_list ap); /** This function is called to output a message to the log. * * In addition to the message this function accepts file/line/function * information. */ WS_DLL_PUBLIC void ws_log_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *format, ...) G_GNUC_PRINTF(6,7); /** This function is called to output a message to the log. * * In addition to the message this function accepts file/line/function * information. */ WS_DLL_PUBLIC void ws_logv_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *format, va_list ap); WS_DLL_PUBLIC WS_NORETURN void ws_log_fatal_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *format, ...) G_GNUC_PRINTF(6,7); /* * The if condition avoids -Wunused warnings for variables used only with * WS_DEBUG, typically inside a ws_debug() call. The compiler will * optimize away the dead execution branch. */ #define _LOG_IF_ACTIVE(active, level, file, line, func, ...) \ do { \ if (active) { \ ws_log_full(_LOG_DOMAIN, level, \ file, line, func, \ __VA_ARGS__); \ } \ } while (0) #define _LOG_FULL(active, level, ...) \ _LOG_IF_ACTIVE(active, level, __FILE__, __LINE__, __func__, __VA_ARGS__) #define _LOG_SIMPLE(active, level, ...) \ _LOG_IF_ACTIVE(active, level, NULL, -1, NULL, __VA_ARGS__) /** Logs with "error" level. * * Accepts a format string and includes the file and function name. * * "error" is always fatal and terminates the program with a coredump. */ #define ws_error(...) \ ws_log_fatal_full(_LOG_DOMAIN, LOG_LEVEL_ERROR, \ __FILE__, __LINE__, __func__, __VA_ARGS__) /** Logs with "critical" level. * * Accepts a format string and includes the file and function name. */ #define ws_critical(...) \ _LOG_FULL(true, LOG_LEVEL_CRITICAL, __VA_ARGS__) /** Logs with "warning" level. * * Accepts a format string and includes the file and function name. */ #define ws_warning(...) \ _LOG_FULL(true, LOG_LEVEL_WARNING, __VA_ARGS__) /** Logs with "message" level. * * Accepts a format string and *does not* include the file and function * name. This is the default log level. */ #define ws_message(...) \ _LOG_SIMPLE(true, LOG_LEVEL_MESSAGE, __VA_ARGS__) /** Logs with "info" level. * * Accepts a format string and includes the file and function name. */ #define ws_info(...) \ _LOG_FULL(true, LOG_LEVEL_INFO, __VA_ARGS__) /** Logs with "debug" level. * * Accepts a format string and includes the file and function name. */ #define ws_debug(...) \ _LOG_FULL(_LOG_DEBUG_ENABLED, LOG_LEVEL_DEBUG, __VA_ARGS__) /** Logs with "noisy" level. * * Accepts a format string and includes the file and function name. */ #define ws_noisy(...) \ _LOG_FULL(_LOG_DEBUG_ENABLED, LOG_LEVEL_NOISY, __VA_ARGS__) /** Used for temporary debug print outs, always active. */ #define WS_DEBUG_HERE(...) \ _LOG_FULL(true, LOG_LEVEL_ECHO, __VA_ARGS__) WS_DLL_PUBLIC void ws_log_utf8_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *string, ssize_t length, const char *endptr); #define ws_log_utf8(str, len, endptr) \ do { \ if (_LOG_DEBUG_ENABLED) { \ ws_log_utf8_full(LOG_DOMAIN_UTF_8, LOG_LEVEL_DEBUG, \ __FILE__, __LINE__, __func__, \ str, len, endptr); \ } \ } while (0) /** This function is called to log a buffer (bytes array). * * Accepts an optional 'msg' argument to provide a description. */ WS_DLL_PUBLIC void ws_log_buffer_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const uint8_t *buffer, size_t size, size_t max_bytes_len, const char *msg); #define ws_log_buffer(buf, size) \ do { \ if (_LOG_DEBUG_ENABLED) { \ ws_log_buffer_full(_LOG_DOMAIN, LOG_LEVEL_DEBUG, \ __FILE__, __LINE__, __func__, \ buf, size, 36, #buf); \ } \ } while (0) /** Auxiliary function to write custom logging functions. * * This function is the same as ws_log_full() but does not perform any * domain/level filtering to avoid a useless double activation check. * It should only be used in conjunction with a pre-check using * ws_log_msg_is_active(). */ WS_DLL_PUBLIC void ws_log_write_always_full(const char *domain, enum ws_log_level level, const char *file, long line, const char *func, const char *format, ...) G_GNUC_PRINTF(6,7); /** Define an auxiliary file pointer where messages should be written. * * This file, if set, functions in addition to the registered or * default log writer. */ WS_DLL_PUBLIC void ws_log_add_custom_file(FILE *fp); WS_DLL_PUBLIC void ws_log_print_usage(FILE *fp); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __WSLOG_H__ */
C/C++
wireshark/wsutil/ws_assert.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_ASSERT_H__ #define __WS_ASSERT_H__ #include <ws_symbol_export.h> #include <ws_attributes.h> #include <stdbool.h> #include <string.h> #include <wsutil/wslog.h> #ifdef WS_DEBUG #define _ASSERT_ENABLED true #else #define _ASSERT_ENABLED false #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * We don't want to execute the expression with !WS_DEBUG because * it might be time and space costly and the goal here is to optimize for * !WS_DEBUG. However removing it completely is not good enough * because it might generate many unused variable warnings. So we use * if (false) and let the compiler optimize away the dead execution branch. */ #define _ASSERT_IF_ACTIVE(active, expr) \ do { \ if ((active) && !(expr)) \ ws_error("assertion failed: %s", #expr); \ } while (0) /* * ws_abort_if_fail() is not conditional on WS_DEBUG. * Usually used to appease a static analyzer. */ #define ws_abort_if_fail(expr) \ _ASSERT_IF_ACTIVE(true, expr) /* * ws_assert() cannot produce side effects, otherwise code will * behave differently because of WS_DEBUG, and probably introduce * some difficult to track bugs. */ #define ws_assert(expr) \ _ASSERT_IF_ACTIVE(_ASSERT_ENABLED, expr) #define ws_assert_streq(s1, s2) \ ws_assert((s1) && (s2) && strcmp((s1), (s2)) == 0) #define ws_assert_utf8(str, len) \ do { \ const char *__assert_endptr; \ if (_ASSERT_ENABLED && \ !g_utf8_validate(str, len, &__assert_endptr)) { \ ws_log_utf8_full(LOG_DOMAIN_UTF_8, LOG_LEVEL_ERROR, \ __FILE__, __LINE__, __func__, \ str, len, __assert_endptr); \ } \ } while (0) /* * We don't want to disable ws_assert_not_reached() with WS_DEBUG. * That would blast compiler warnings everywhere for no benefit, not * even a miniscule performance gain. Reaching this function is always * a programming error and will unconditionally abort execution. * * Note: With g_assert_not_reached() if the compiler supports unreachable * built-ins (which recent versions of GCC and MSVC do) there is no warning * blast with g_assert_not_reached() and G_DISABLE_ASSERT. However if that * is not the case then g_assert_not_reached() is simply (void)0 and that * causes the spurious warnings, because the compiler can't tell anymore * that a certain code path is not used. We avoid that with * ws_assert_not_reached(). There is no reason to ever use a no-op here. */ #define ws_assert_not_reached() \ ws_error("assertion \"not reached\" failed") #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __WS_ASSERT_H__ */
C/C++
wireshark/wsutil/ws_cpuid.h
/** @file * Get the CPU info on x86 processors that support it * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ /* * Get CPU info on platforms where the x86 cpuid instruction can be used. * * Skip 32-bit versions for GCC and Clang, as older IA-32 processors don't * have cpuid. * * Intel has documented the CPUID instruction in the "Intel(r) 64 and IA-32 * Architectures Developer's Manual" at * * https://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-2a-manual.html * * The ws_cpuid() routine will return 0 if cpuinfo isn't available, including * on non-x86 platforms and on 32-bit x86 platforms with GCC and Clang, as * well as non-MSVC and non-GCC-or-Clang platforms. * * The "selector" argument to ws_cpuid() is the "initial EAX value" for the * instruction. The initial ECX value is 0. * * The "CPUInfo" argument points to 4 32-bit values into which the * resulting values of EAX, EBX, ECX, and EDX are store, in order. */ #include "ws_attributes.h" #if defined(_MSC_VER) /* MSVC */ /* * XXX - do the same IA-32 (which doesn't have CPUID prior to some versions * of the 80486 and all versions of the 80586^Woriginal Pentium) vs. * x86-64 (which always has CPUID) stuff that we do with GCC/Clang? * * You will probably not be happy running current versions of Wireshark * on an 80386 or 80486 machine, and we're dropping support for IA-32 * on Windows anyway, so the answer is probably "no". */ #if defined(_M_IX86) || defined(_M_X64) static gboolean ws_cpuid(guint32 *CPUInfo, guint32 selector) { /* https://docs.microsoft.com/en-us/cpp/intrinsics/cpuid-cpuidex */ CPUInfo[0] = CPUInfo[1] = CPUInfo[2] = CPUInfo[3] = 0; __cpuid((int *) CPUInfo, selector); /* XXX, how to check if it's supported on MSVC? just in case clear all flags above */ return TRUE; } #else /* not x86 */ static gboolean ws_cpuid(guint32 *CPUInfo _U_, int selector _U_) { /* Not x86, so no cpuid instruction */ return FALSE; } #endif #elif defined(__GNUC__) /* GCC/clang */ #if defined(__x86_64__) static inline gboolean ws_cpuid(guint32 *CPUInfo, int selector) { __asm__ __volatile__("cpuid" : "=a" (CPUInfo[0]), "=b" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3]) : "a" (selector), "c" (0)); return TRUE; } #elif defined(__i386__) static gboolean ws_cpuid(guint32 *CPUInfo _U_, int selector _U_) { /* * TODO: need a test if older processors have the cpuid instruction. * * The correct way to test for this, according to the Intel64/IA-32 * documentation from Intel, in section 17.1 "USING THE CPUID * INSTRUCTION", is to try to change the ID bit (bit 21) in * EFLAGS. If it can be changed, the machine supports CPUID, * otherwise it doesn't. * * Some 486's, and all subsequent processors, support CPUID. * * For those who are curious, the way you distinguish between * an 80386 and an 80486 is to try to set the flag in EFLAGS * that causes unaligned accesses to fault - that's bit 18. * However, if the SMAP bit is set in CR4, that bit controls * whether explicit supervisor-mode access to user-mode pages * are allowed, so that should presumably only be done in a * very controlled environment, such as the system boot process. * * So, if you want to find out what type of CPU the system has, * it's probably best to ask the OS, if it supplies the result * of any CPU type testing it's done. */ return FALSE; } #else /* not x86 */ static gboolean ws_cpuid(guint32 *CPUInfo _U_, int selector _U_) { /* Not x86, so no cpuid instruction */ return FALSE; } #endif #else /* Other compilers */ static gboolean ws_cpuid(guint32 *CPUInfo _U_, int selector _U_) { return FALSE; } #endif static int ws_cpuid_sse42(void) { guint32 CPUInfo[4]; if (!ws_cpuid(CPUInfo, 1)) return 0; /* in ECX bit 20 toggled on */ return (CPUInfo[2] & (1 << 20)); }
C
wireshark/wsutil/ws_getopt.c
/* * musl as a whole is licensed under the following standard MIT license: * * ---------------------------------------------------------------------- * Copyright © 2005-2020 Rich Felker, et al. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ---------------------------------------------------------------------- */ #include <wsutil/ws_getopt.h> #include <stddef.h> #include <stdlib.h> #include <limits.h> #include <stdio.h> #include <string.h> #include <wchar.h> #include <ws_codepoints.h> char *ws_optarg; int ws_optind=1, ws_opterr=1, ws_optopt, ws_optpos, ws_optreset=0; static void __getopt_msg(const char *prog, const char *errstr, const char *optbuf, size_t optsize) { FILE *f = stderr; if ((fputs(prog, f) < 0) || (fputs(errstr, f) < 0) || (fwrite(optbuf, sizeof(char), optsize, f) != optsize)) { return; } putc('\n', f); } static void permute(char *const *argv, int dest, int src) { char **av = (char **)argv; char *tmp = av[src]; int i; for (i=src; i>dest; i--) av[i] = av[i-1]; av[dest] = tmp; } int ws_getopt(int argc, char * const argv[], const char *optstring) { int i; wchar_t c, d; int k, l; char *optchar; if (!ws_optind || ws_optreset) { ws_optreset = 0; ws_optpos = 0; ws_optind = 1; } if (ws_optind >= argc || !argv[ws_optind]) return -1; if (argv[ws_optind][0] != '-') { if (optstring[0] == '-') { ws_optarg = argv[ws_optind++]; return 1; } return -1; } if (!argv[ws_optind][1]) return -1; if (argv[ws_optind][1] == '-' && !argv[ws_optind][2]) { ws_optind++; return -1; } if (!ws_optpos) ws_optpos++; if ((k = mbtowc(&c, argv[ws_optind]+ws_optpos, MB_LEN_MAX)) < 0) { k = 1; c = UNICODE_REPLACEMENT_CHARACTER; /* replacement char */ } optchar = argv[ws_optind]+ws_optpos; ws_optpos += k; if (!argv[ws_optind][ws_optpos]) { ws_optind++; ws_optpos = 0; } if (optstring[0] == '-' || optstring[0] == '+') optstring++; i = 0; d = 0; do { l = mbtowc(&d, optstring+i, MB_LEN_MAX); if (l>0) i+=l; else i++; } while (l && d != c); if (d != c || c == ':') { ws_optopt = c; if (optstring[0] != ':' && ws_opterr) __getopt_msg(argv[0], ": unrecognized option: ", optchar, k); return '?'; } if (optstring[i] == ':') { ws_optarg = 0; if (optstring[i+1] != ':' || ws_optpos) { ws_optarg = argv[ws_optind++] + ws_optpos; ws_optpos = 0; } if (ws_optind > argc) { ws_optopt = c; if (optstring[0] == ':') return ':'; if (ws_opterr) __getopt_msg(argv[0], ": option requires an argument: ", optchar, k); return '?'; } } return c; } static int __getopt_long_core(int argc, char *const *argv, const char *optstring, const struct ws_option *longopts, int *idx, int longonly); static int __getopt_long(int argc, char *const *argv, const char *optstring, const struct ws_option *longopts, int *idx, int longonly) { int ret, skipped, resumed; if (!ws_optind || ws_optreset) { ws_optreset = 0; ws_optpos = 0; ws_optind = 1; } if (ws_optind >= argc || !argv[ws_optind]) return -1; skipped = ws_optind; if (optstring[0] != '+' && optstring[0] != '-') { int i; for (i=ws_optind; ; i++) { if (i >= argc || !argv[i]) return -1; if (argv[i][0] == '-' && argv[i][1]) break; } ws_optind = i; } resumed = ws_optind; ret = __getopt_long_core(argc, argv, optstring, longopts, idx, longonly); if (resumed > skipped) { int i, cnt = ws_optind-resumed; for (i=0; i<cnt; i++) permute(argv, skipped, ws_optind-1); ws_optind = skipped + cnt; } return ret; } static int __getopt_long_core(int argc, char *const *argv, const char *optstring, const struct ws_option *longopts, int *idx, int longonly) { ws_optarg = 0; if (longopts && argv[ws_optind][0] == '-' && ((longonly && argv[ws_optind][1] && argv[ws_optind][1] != '-') || (argv[ws_optind][1] == '-' && argv[ws_optind][2]))) { int colon = optstring[optstring[0]=='+'||optstring[0]=='-']==':'; int i, cnt, match = -1; char *arg = NULL, *opt, *start = argv[ws_optind]+1; for (cnt=i=0; longopts[i].name; i++) { const char *name = longopts[i].name; opt = start; if (*opt == '-') opt++; while (*opt && *opt != '=' && *opt == *name) { name++; opt++; } if (*opt && *opt != '=') continue; arg = opt; match = i; if (!*name) { cnt = 1; break; } cnt++; } if (cnt==1 && longonly && arg-start == mblen(start, MB_LEN_MAX)) { ptrdiff_t l = arg - start; for (i=0; optstring[i]; i++) { ptrdiff_t j; for (j=0; j<l && start[j]==optstring[i+j]; j++); if (j==l) { cnt++; break; } } } if (cnt==1) { i = match; opt = arg; ws_optind++; if (*opt == '=') { if (!longopts[i].has_arg) { ws_optopt = longopts[i].val; if (colon || !ws_opterr) return '?'; __getopt_msg(argv[0], ": option does not take an argument: ", longopts[i].name, strlen(longopts[i].name)); return '?'; } ws_optarg = opt+1; } else if (longopts[i].has_arg == ws_required_argument) { if (!(ws_optarg = argv[ws_optind])) { ws_optopt = longopts[i].val; if (colon) return ':'; if (!ws_opterr) return '?'; __getopt_msg(argv[0], ": option requires an argument: ", longopts[i].name, strlen(longopts[i].name)); return '?'; } ws_optind++; } if (idx) *idx = i; if (longopts[i].flag) { *longopts[i].flag = longopts[i].val; return 0; } return longopts[i].val; } if (argv[ws_optind][1] == '-') { ws_optopt = 0; if (!colon && ws_opterr) __getopt_msg(argv[0], cnt ? ": option is ambiguous: " : ": unrecognized option: ", argv[ws_optind]+2, strlen(argv[ws_optind]+2)); ws_optind++; return '?'; } } return ws_getopt(argc, argv, optstring); } int ws_getopt_long(int argc, char *const *argv, const char *optstring, const struct ws_option *longopts, int *idx) { return __getopt_long(argc, argv, optstring, longopts, idx, 0); } int ws_getopt_long_only(int argc, char *const *argv, const char *optstring, const struct ws_option *longopts, int *idx) { return __getopt_long(argc, argv, optstring, longopts, idx, 1); }
C/C++
wireshark/wsutil/ws_getopt.h
/** @file * * musl as a whole is licensed under the following standard MIT license: * * ---------------------------------------------------------------------- * Copyright © 2005-2020 Rich Felker, et al. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ---------------------------------------------------------------------- */ #ifndef _WS_GETOPT_H_ #define _WS_GETOPT_H_ #include <ws_symbol_export.h> #ifdef __cplusplus extern "C" { #endif WS_DLL_PUBLIC int ws_getopt(int, char * const [], const char *); WS_DLL_PUBLIC char *ws_optarg; WS_DLL_PUBLIC int ws_optind, ws_opterr, ws_optopt, ws_optpos, ws_optreset; struct ws_option { const char *name; int has_arg; int *flag; int val; }; WS_DLL_PUBLIC int ws_getopt_long(int, char *const *, const char *, const struct ws_option *, int *); WS_DLL_PUBLIC int ws_getopt_long_only(int, char *const *, const char *, const struct ws_option *, int *); #define ws_no_argument 0 #define ws_required_argument 1 #define ws_optional_argument 2 #ifdef __cplusplus } #endif #endif
C
wireshark/wsutil/ws_mempbrk.c
/* ws_mempbrk.c * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" /* see bug 10798: there is a bug in the compiler the buildbots use for Mac OSX and SSE4.2, so we're not going to use SSE4.2 with Mac OSX right now, for older Mac OSX compilers. */ #ifdef __APPLE__ #if defined(__clang__) && (__clang_major__ >= 6) /* allow HAVE_SSE4_2 to be used for clang 6.0+ case because we know it works */ #else /* don't allow it otherwise, for Mac OSX */ #undef HAVE_SSE4_2 #endif #endif #include "ws_mempbrk.h" #include "ws_mempbrk_int.h" void ws_mempbrk_compile(ws_mempbrk_pattern* pattern, const gchar *needles) { const gchar *n = needles; while (*n) { pattern->patt[(int)*n] = 1; n++; } #ifdef HAVE_SSE4_2 ws_mempbrk_sse42_compile(pattern, needles); #endif } const guint8 * ws_mempbrk_portable_exec(const guint8* haystack, size_t haystacklen, const ws_mempbrk_pattern* pattern, guchar *found_needle) { const guint8 *haystack_end = haystack + haystacklen; while (haystack < haystack_end) { if (pattern->patt[*haystack]) { if (found_needle) *found_needle = *haystack; return haystack; } haystack++; } return NULL; } WS_DLL_PUBLIC const guint8 * ws_mempbrk_exec(const guint8* haystack, size_t haystacklen, const ws_mempbrk_pattern* pattern, guchar *found_needle) { #ifdef HAVE_SSE4_2 if (haystacklen >= 16 && pattern->use_sse42) return ws_mempbrk_sse42_exec(haystack, haystacklen, pattern, found_needle); #endif return ws_mempbrk_portable_exec(haystack, haystacklen, pattern, found_needle); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
C/C++
wireshark/wsutil/ws_mempbrk.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_MEMPBRK_H__ #define __WS_MEMPBRK_H__ #include <wireshark.h> #ifdef HAVE_SSE4_2 #include <emmintrin.h> #endif /** The pattern object used for ws_mempbrk_exec(). */ typedef struct { gchar patt[256]; #ifdef HAVE_SSE4_2 gboolean use_sse42; __m128i mask; #endif } ws_mempbrk_pattern; /** Compile the pattern for the needles to find using ws_mempbrk_exec(). */ WS_DLL_PUBLIC void ws_mempbrk_compile(ws_mempbrk_pattern* pattern, const gchar *needles); /** Scan for the needles specified by the compiled pattern. */ WS_DLL_PUBLIC const guint8 *ws_mempbrk_exec(const guint8* haystack, size_t haystacklen, const ws_mempbrk_pattern* pattern, guchar *found_needle); #endif /* __WS_MEMPBRK_H__ */
C/C++
wireshark/wsutil/ws_mempbrk_int.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_MEMPBRK_INT_H__ #define __WS_MEMPBRK_INT_H__ const guint8 *ws_mempbrk_portable_exec(const guint8* haystack, size_t haystacklen, const ws_mempbrk_pattern* pattern, guchar *found_needle); #ifdef HAVE_SSE4_2 void ws_mempbrk_sse42_compile(ws_mempbrk_pattern* pattern, const gchar *needles); const char *ws_mempbrk_sse42_exec(const char* haystack, size_t haystacklen, const ws_mempbrk_pattern* pattern, guchar *found_needle); #endif #endif /* __WS_MEMPBRK_INT_H__ */
C
wireshark/wsutil/ws_mempbrk_sse42.c
/* strcspn with SSE4.2 intrinsics Copyright (C) 2009-2014 Free Software Foundation, Inc. Contributed by Intel Corporation. This file is part of the GNU C Library. SPDX-License-Identifier: LGPL-2.1-or-later */ #include "config.h" #ifdef HAVE_SSE4_2 #include <glib.h> #include "ws_cpuid.h" #ifdef _WIN32 #include <tmmintrin.h> #endif #include <nmmintrin.h> #include <string.h> #include "ws_mempbrk.h" #include "ws_mempbrk_int.h" /* __has_feature(address_sanitizer) is used later for Clang, this is for * compatibility with other compilers (such as GCC and MSVC) */ #ifndef __has_feature # define __has_feature(x) 0 #endif #define cast_128aligned__m128i(p) ((const __m128i *) (const void *) (p)) /* Helper for variable shifts of SSE registers. Copyright (C) 2010 Free Software Foundation, Inc. */ static const gint8 ___m128i_shift_right[31] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static inline __m128i __m128i_shift_right (__m128i value, unsigned long int offset) { /* _mm_loadu_si128() works with unaligned data, cast safe */ return _mm_shuffle_epi8 (value, _mm_loadu_si128 (cast_128aligned__m128i(___m128i_shift_right + offset))); } void ws_mempbrk_sse42_compile(ws_mempbrk_pattern* pattern, const gchar *needles) { size_t length = strlen(needles); pattern->use_sse42 = ws_cpuid_sse42() && (length <= 16); if (pattern->use_sse42) { pattern->mask = _mm_setzero_si128(); memcpy(&(pattern->mask), needles, length); } } /* We use 0x2: _SIDD_SBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_POSITIVE_POLARITY | _SIDD_LEAST_SIGNIFICANT on pcmpistri to compare xmm/mem128 0 1 2 3 4 5 6 7 8 9 A B C D E F X X X X X X X X X X X X X X X X against xmm 0 1 2 3 4 5 6 7 8 9 A B C D E F A A A A A A A A A A A A A A A A to find out if the first 16byte data element has any byte A and the offset of the first byte. There are 3 cases: 1. The first 16byte data element has the byte A at the offset X. 2. The first 16byte data element has EOS and doesn't have the byte A. 3. The first 16byte data element is valid and doesn't have the byte A. Here is the table of ECX, CFlag, ZFlag and SFlag for 2 cases: 1 X 1 0/1 0 2 16 0 1 0 3 16 0 0 0 We exit from the loop for cases 1 and 2 with jbe which branches when either CFlag or ZFlag is 1. If CFlag == 1, ECX has the offset X for case 1. */ const char * ws_mempbrk_sse42_exec(const char *haystack, size_t haystacklen, const ws_mempbrk_pattern* pattern, guchar *found_needle) { const char *aligned; int offset; offset = (int) ((size_t) haystack & 15); aligned = (const char *) ((size_t) haystack & -16L); if (offset != 0) { /* Check partial string. cast safe it's 16B aligned */ __m128i value = __m128i_shift_right (_mm_load_si128 (cast_128aligned__m128i(aligned)), offset); int length = _mm_cmpistri (pattern->mask, value, 0x2); /* No need to check ZFlag since ZFlag is always 1. */ int cflag = _mm_cmpistrc (pattern->mask, value, 0x2); /* XXX: why does this compare value with value? */ int idx = _mm_cmpistri (value, value, 0x3a); if (cflag) { if (found_needle) *found_needle = *(haystack + length); return haystack + length; } /* Find where the NULL terminator is. */ if (idx < 16 - offset) { /* found NUL @ 'idx', need to switch to slower mempbrk */ return ws_mempbrk_portable_exec(haystack + idx + 1, haystacklen - idx - 1, pattern, found_needle); /* haystacklen is bigger than 16 & idx < 16 so no underflow here */ } aligned += 16; haystacklen -= (16 - offset); } else aligned = haystack; while (haystacklen >= 16) { __m128i value = _mm_load_si128 (cast_128aligned__m128i(aligned)); int idx = _mm_cmpistri (pattern->mask, value, 0x2); int cflag = _mm_cmpistrc (pattern->mask, value, 0x2); int zflag = _mm_cmpistrz (pattern->mask, value, 0x2); if (cflag) { if (found_needle) *found_needle = *(aligned + idx); return aligned + idx; } if (zflag) { /* found NUL, need to switch to slower mempbrk */ return ws_mempbrk_portable_exec(aligned, haystacklen, pattern, found_needle); } aligned += 16; haystacklen -= 16; } /* XXX, use mempbrk_slow here? */ return ws_mempbrk_portable_exec(aligned, haystacklen, pattern, found_needle); } #endif /* HAVE_SSE4_2 */ /* * Editor modelines * * Local Variables: * c-basic-offset: 2 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=2 tabstop=8 expandtab: * :indentSize=2:tabSize=8:noTabs=true: */
C
wireshark/wsutil/ws_pipe.c
/* ws_pipe.c * * Routines for handling pipes. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <config.h> #define WS_LOG_DOMAIN LOG_DOMAIN_CAPTURE #include "wsutil/ws_pipe.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <windows.h> #include <io.h> #include <fcntl.h> /* for _O_BINARY */ #include <wsutil/win32-utils.h> #else #include <unistd.h> #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #endif #ifdef __linux__ #define HAS_G_SPAWN_LINUX_THREAD_SAFETY_BUG #include <fcntl.h> #include <sys/syscall.h> /* for syscall and SYS_getdents64 */ #include <wsutil/file_util.h> /* for ws_open -> open to pacify checkAPIs.pl */ #endif #include "wsutil/filesystem.h" #include "wsutil/wslog.h" #ifdef HAS_G_SPAWN_LINUX_THREAD_SAFETY_BUG struct linux_dirent64 { guint64 d_ino; /* 64-bit inode number */ guint64 d_off; /* 64-bit offset to next structure */ unsigned short d_reclen; /* Size of this dirent */ unsigned char d_type; /* File type */ char d_name[]; /* Filename (null-terminated) */ }; /* Async-signal-safe string to integer conversion. */ static gint filename_to_fd(const char *p) { char c; int fd = 0; const int cutoff = G_MAXINT / 10; const int cutlim = G_MAXINT % 10; if (*p == '\0') return -1; while ((c = *p++) != '\0') { if (!g_ascii_isdigit(c)) return -1; c -= '0'; /* Check for overflow. */ if (fd > cutoff || (fd == cutoff && c > cutlim)) return -1; fd = fd * 10 + c; } return fd; } static void close_non_standard_fds_linux(gpointer user_data _U_) { /* * GLib 2.14.2 and newer (up to at least GLib 2.58.1) on Linux with multiple * threads can deadlock in the child process due to use of opendir (which * is not async-signal-safe). To avoid this, disable the broken code path * and manually close file descriptors using async-signal-safe code only. * Use CLOEXEC to allow reporting of execve errors to the parent via a pipe. * https://gitlab.gnome.org/GNOME/glib/issues/1014 * https://gitlab.gnome.org/GNOME/glib/merge_requests/490 */ int dir_fd = ws_open("/proc/self/fd", O_RDONLY | O_DIRECTORY); if (dir_fd >= 0) { char buf[4096]; int nread, fd; struct linux_dirent64 *de; while ((nread = (int) syscall(SYS_getdents64, dir_fd, buf, sizeof(buf))) > 0) { for (int pos = 0; pos < nread; pos += de->d_reclen) { de = (struct linux_dirent64 *)(buf + pos); fd = filename_to_fd(de->d_name); if (fd > STDERR_FILENO && fd != dir_fd) { /* Close all other (valid) file descriptors above stderr. */ fcntl(fd, F_SETFD, FD_CLOEXEC); } } } close(dir_fd); } else { /* Slow fallback in case /proc is not mounted */ for (int fd = STDERR_FILENO + 1; fd < getdtablesize(); fd++) { fcntl(fd, F_SETFD, FD_CLOEXEC); } } } #endif #ifdef _WIN32 static ULONG pipe_serial_number; /* Alternative for CreatePipe() where read handle is opened with FILE_FLAG_OVERLAPPED */ static gboolean ws_pipe_create_overlapped_read(HANDLE *read_pipe_handle, HANDLE *write_pipe_handle, SECURITY_ATTRIBUTES *sa, DWORD suggested_buffer_size) { HANDLE read_pipe, write_pipe; guchar *name = ws_strdup_printf("\\\\.\\Pipe\\WiresharkWsPipe.%08lx.%08lx", GetCurrentProcessId(), InterlockedIncrement(&pipe_serial_number)); gunichar2 *wname = g_utf8_to_utf16(name, -1, NULL, NULL, NULL); g_free(name); read_pipe = CreateNamedPipe(wname, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_WAIT, 1, suggested_buffer_size, suggested_buffer_size, 0, sa); if (INVALID_HANDLE_VALUE == read_pipe) { g_free(wname); return FALSE; } write_pipe = CreateFile(wname, GENERIC_WRITE, 0, sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == write_pipe) { DWORD error = GetLastError(); CloseHandle(read_pipe); SetLastError(error); g_free(wname); return FALSE; } *read_pipe_handle = read_pipe; *write_pipe_handle = write_pipe; g_free(wname); return(TRUE); } #endif /** * Helper to convert a command and argument list to an NULL-terminated 'argv' * array, suitable for g_spawn_sync and friends. Free with g_strfreev. */ static gchar ** convert_to_argv(const char *command, int args_count, char *const *args) { gchar **argv = g_new(gchar *, args_count + 2); // The caller does not seem to modify this, but g_spawn_sync uses 'gchar **' // as opposed to 'const gchar **', so just to be sure clone it. argv[0] = g_strdup(command); for (int i = 0; i < args_count; i++) { // Empty arguments may indicate a bug in Wireshark. Extcap for example // omits arguments when their string value is empty. On Windows, empty // arguments would silently be ignored because protect_arg returns an // empty string, therefore we print a warning here. if (!*args[i]) { ws_warning("Empty argument %d in arguments list", i); } argv[1 + i] = g_strdup(args[i]); } argv[args_count + 1] = NULL; return argv; } /** * Convert a non-empty NULL-terminated array of command and arguments to a * string for displaying purposes. On Windows, the returned string is properly * escaped and can be executed directly. */ static gchar * convert_to_command_line(gchar **argv) { GString *command_line = g_string_sized_new(200); #ifdef _WIN32 // The first argument must always be quoted even if it does not contain // special characters or else CreateProcess might consider arguments as part // of the executable. gchar *quoted_arg = protect_arg(argv[0]); if (quoted_arg[0] != '"') { g_string_append_c(command_line, '"'); g_string_append(command_line, quoted_arg); g_string_append_c(command_line, '"'); } else { g_string_append(command_line, quoted_arg); } g_free(quoted_arg); for (int i = 1; argv[i]; i++) { quoted_arg = protect_arg(argv[i]); g_string_append_c(command_line, ' '); g_string_append(command_line, quoted_arg); g_free(quoted_arg); } #else for (int i = 0; argv[i]; i++) { gchar *quoted_arg = g_shell_quote(argv[i]); if (i != 0) { g_string_append_c(command_line, ' '); } g_string_append(command_line, quoted_arg); g_free(quoted_arg); } #endif return g_string_free(command_line, FALSE); } gboolean ws_pipe_spawn_sync(const gchar *working_directory, const gchar *command, gint argc, gchar **args, gchar **command_output) { gboolean status = FALSE; gboolean result = FALSE; gchar *local_output = NULL; #ifdef _WIN32 #define BUFFER_SIZE 16384 STARTUPINFO info; PROCESS_INFORMATION processInfo; SECURITY_ATTRIBUTES sa; HANDLE child_stdout_rd = NULL; HANDLE child_stdout_wr = NULL; HANDLE child_stderr_rd = NULL; HANDLE child_stderr_wr = NULL; HANDLE inherit_handles[2]; OVERLAPPED stdout_overlapped; OVERLAPPED stderr_overlapped; #else gint exit_status = 0; #endif gchar **argv = convert_to_argv(command, argc, args); gchar *command_line = convert_to_command_line(argv); ws_debug("command line: %s", command_line); guint64 start_time = g_get_monotonic_time(); #ifdef _WIN32 /* Setup overlapped structures. Create Manual Reset events, initially not signalled */ memset(&stdout_overlapped, 0, sizeof(OVERLAPPED)); memset(&stderr_overlapped, 0, sizeof(OVERLAPPED)); stdout_overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!stdout_overlapped.hEvent) { g_free(command_line); g_strfreev(argv); ws_debug("Could not create stdout overlapped event"); return FALSE; } stderr_overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!stderr_overlapped.hEvent) { CloseHandle(stdout_overlapped.hEvent); g_free(command_line); g_strfreev(argv); ws_debug("Could not create stderr overlapped event"); return FALSE; } memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES)); sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = NULL; if (!ws_pipe_create_overlapped_read(&child_stdout_rd, &child_stdout_wr, &sa, 0)) { CloseHandle(stdout_overlapped.hEvent); CloseHandle(stderr_overlapped.hEvent); g_free(command_line); g_strfreev(argv); ws_debug("Could not create stdout handle"); return FALSE; } if (!ws_pipe_create_overlapped_read(&child_stderr_rd, &child_stderr_wr, &sa, 0)) { CloseHandle(stdout_overlapped.hEvent); CloseHandle(stderr_overlapped.hEvent); CloseHandle(child_stdout_rd); CloseHandle(child_stdout_wr); g_free(command_line); g_strfreev(argv); ws_debug("Could not create stderr handle"); return FALSE; } inherit_handles[0] = child_stderr_wr; inherit_handles[1] = child_stdout_wr; memset(&processInfo, 0, sizeof(PROCESS_INFORMATION)); memset(&info, 0, sizeof(STARTUPINFO)); info.cb = sizeof(STARTUPINFO); info.hStdError = child_stderr_wr; info.hStdOutput = child_stdout_wr; info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; info.wShowWindow = SW_HIDE; if (win32_create_process(NULL, command_line, NULL, NULL, G_N_ELEMENTS(inherit_handles), inherit_handles, CREATE_NEW_CONSOLE, NULL, working_directory, &info, &processInfo)) { gchar* stdout_buffer = (gchar*)g_malloc(BUFFER_SIZE); gchar* stderr_buffer = (gchar*)g_malloc(BUFFER_SIZE); DWORD dw; DWORD bytes_read; GString *output_string = g_string_new(NULL); gboolean process_finished = FALSE; gboolean pending_stdout = TRUE; gboolean pending_stderr = TRUE; /* Start asynchronous reads from child process stdout and stderr */ if (!ReadFile(child_stdout_rd, stdout_buffer, BUFFER_SIZE, NULL, &stdout_overlapped)) { if (GetLastError() != ERROR_IO_PENDING) { ws_debug("ReadFile on child stdout pipe failed. Error %ld", GetLastError()); pending_stdout = FALSE; } } if (!ReadFile(child_stderr_rd, stderr_buffer, BUFFER_SIZE, NULL, &stderr_overlapped)) { if (GetLastError() != ERROR_IO_PENDING) { ws_debug("ReadFile on child stderr pipe failed. Error %ld", GetLastError()); pending_stderr = FALSE; } } for (;;) { HANDLE handles[3]; DWORD n_handles = 0; if (!process_finished) { handles[n_handles++] = processInfo.hProcess; } if (pending_stdout) { handles[n_handles++] = stdout_overlapped.hEvent; } if (pending_stderr) { handles[n_handles++] = stderr_overlapped.hEvent; } if (!n_handles) { /* No more things to wait */ break; } dw = WaitForMultipleObjects(n_handles, handles, FALSE, INFINITE); if (dw < (WAIT_OBJECT_0 + n_handles)) { int i = dw - WAIT_OBJECT_0; if (handles[i] == processInfo.hProcess) { /* Process finished but there might still be unread data in the pipe. * Close the write pipes, so ReadFile does not wait indefinitely. */ CloseHandle(child_stdout_wr); CloseHandle(child_stderr_wr); process_finished = TRUE; } else if (handles[i] == stdout_overlapped.hEvent) { bytes_read = 0; if (!GetOverlappedResult(child_stdout_rd, &stdout_overlapped, &bytes_read, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { pending_stdout = FALSE; continue; } ws_debug("GetOverlappedResult on stdout failed. Error %ld", GetLastError()); } if (process_finished && (bytes_read == 0)) { /* We have drained the pipe and there isn't any process that holds active write handle to the pipe. */ pending_stdout = FALSE; continue; } g_string_append_len(output_string, stdout_buffer, bytes_read); if (!ReadFile(child_stdout_rd, stdout_buffer, BUFFER_SIZE, NULL, &stdout_overlapped)) { if (GetLastError() != ERROR_IO_PENDING) { ws_debug("ReadFile on child stdout pipe failed. Error %ld", GetLastError()); pending_stdout = FALSE; } } } else if (handles[i] == stderr_overlapped.hEvent) { /* Discard the stderr data just like non-windows version of this function does. */ bytes_read = 0; if (!GetOverlappedResult(child_stderr_rd, &stderr_overlapped, &bytes_read, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { pending_stderr = FALSE; continue; } ws_debug("GetOverlappedResult on stderr failed. Error %ld", GetLastError()); } if (process_finished && (bytes_read == 0)) { pending_stderr = FALSE; continue; } if (!ReadFile(child_stderr_rd, stderr_buffer, BUFFER_SIZE, NULL, &stderr_overlapped)) { if (GetLastError() != ERROR_IO_PENDING) { ws_debug("ReadFile on child stderr pipe failed. Error %ld", GetLastError()); pending_stderr = FALSE; } } } } else { ws_debug("WaitForMultipleObjects returned 0x%08lX. Error %ld", dw, GetLastError()); } } g_free(stdout_buffer); g_free(stderr_buffer); status = GetExitCodeProcess(processInfo.hProcess, &dw); if (status && dw != 0) { status = FALSE; } local_output = g_string_free(output_string, FALSE); CloseHandle(child_stdout_rd); CloseHandle(child_stderr_rd); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); } else { status = FALSE; CloseHandle(child_stdout_rd); CloseHandle(child_stdout_wr); CloseHandle(child_stderr_rd); CloseHandle(child_stderr_wr); } CloseHandle(stdout_overlapped.hEvent); CloseHandle(stderr_overlapped.hEvent); #else GSpawnFlags flags = (GSpawnFlags)0; GSpawnChildSetupFunc child_setup = NULL; #ifdef HAS_G_SPAWN_LINUX_THREAD_SAFETY_BUG flags = (GSpawnFlags)(flags | G_SPAWN_LEAVE_DESCRIPTORS_OPEN); child_setup = close_non_standard_fds_linux; #endif status = g_spawn_sync(working_directory, argv, NULL, flags, child_setup, NULL, &local_output, NULL, &exit_status, NULL); if (status && exit_status != 0) status = FALSE; #endif ws_debug("%s finished in %.3fms", argv[0], (g_get_monotonic_time() - start_time) / 1000.0); if (status) { if (local_output != NULL) { ws_noisy("spawn output: %s", local_output); if (command_output != NULL) *command_output = g_strdup(local_output); } result = TRUE; } g_free(local_output); g_free(command_line); g_strfreev(argv); return result; } void ws_pipe_init(ws_pipe_t *ws_pipe) { if (!ws_pipe) return; memset(ws_pipe, 0, sizeof(ws_pipe_t)); ws_pipe->pid = WS_INVALID_PID; } GPid ws_pipe_spawn_async(ws_pipe_t *ws_pipe, GPtrArray *args) { GPid pid = WS_INVALID_PID; gint stdin_fd, stdout_fd, stderr_fd; #ifdef _WIN32 STARTUPINFO info; PROCESS_INFORMATION processInfo; SECURITY_ATTRIBUTES sa; HANDLE child_stdin_rd = NULL; HANDLE child_stdin_wr = NULL; HANDLE child_stdout_rd = NULL; HANDLE child_stdout_wr = NULL; HANDLE child_stderr_rd = NULL; HANDLE child_stderr_wr = NULL; HANDLE inherit_handles[3]; #endif // XXX harmonize handling of command arguments for the sync/async functions // and make them const? This array ends with a trailing NULL by the way. gchar **args_array = (gchar **)args->pdata; gchar **argv = convert_to_argv(args_array[0], args->len - 2, args_array + 1); gchar *command_line = convert_to_command_line(argv); ws_debug("command line: %s", command_line); #ifdef _WIN32 sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = NULL; if (!CreatePipe(&child_stdin_rd, &child_stdin_wr, &sa, 0)) { g_free(command_line); g_strfreev(argv); ws_debug("Could not create stdin handle"); return WS_INVALID_PID; } if (!CreatePipe(&child_stdout_rd, &child_stdout_wr, &sa, 0)) { CloseHandle(child_stdin_rd); CloseHandle(child_stdin_wr); g_free(command_line); g_strfreev(argv); ws_debug("Could not create stdout handle"); return WS_INVALID_PID; } if (!CreatePipe(&child_stderr_rd, &child_stderr_wr, &sa, 0)) { CloseHandle(child_stdin_rd); CloseHandle(child_stdin_wr); CloseHandle(child_stdout_rd); CloseHandle(child_stdout_wr); g_free(command_line); g_strfreev(argv); ws_debug("Could not create stderr handle"); return WS_INVALID_PID; } inherit_handles[0] = child_stdin_rd; inherit_handles[1] = child_stderr_wr; inherit_handles[2] = child_stdout_wr; memset(&processInfo, 0, sizeof(PROCESS_INFORMATION)); memset(&info, 0, sizeof(STARTUPINFO)); info.cb = sizeof(STARTUPINFO); info.hStdInput = child_stdin_rd; info.hStdError = child_stderr_wr; info.hStdOutput = child_stdout_wr; info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; info.wShowWindow = SW_HIDE; if (win32_create_process(NULL, command_line, NULL, NULL, G_N_ELEMENTS(inherit_handles), inherit_handles, CREATE_NEW_CONSOLE, NULL, NULL, &info, &processInfo)) { stdin_fd = _open_osfhandle((intptr_t)(child_stdin_wr), _O_BINARY); stdout_fd = _open_osfhandle((intptr_t)(child_stdout_rd), _O_BINARY); stderr_fd = _open_osfhandle((intptr_t)(child_stderr_rd), _O_BINARY); pid = processInfo.hProcess; CloseHandle(processInfo.hThread); } else { CloseHandle(child_stdin_wr); CloseHandle(child_stdout_rd); CloseHandle(child_stderr_rd); } /* We no longer need other (child) end of pipes. The child process holds * its own handles that will be closed on process exit. However, we have * to close *our* handles as otherwise read() on stdout_fd and stderr_fd * will block indefinitely after the process exits. */ CloseHandle(child_stdin_rd); CloseHandle(child_stdout_wr); CloseHandle(child_stderr_wr); #else GError *error = NULL; GSpawnFlags flags = G_SPAWN_DO_NOT_REAP_CHILD; GSpawnChildSetupFunc child_setup = NULL; #ifdef HAS_G_SPAWN_LINUX_THREAD_SAFETY_BUG flags = (GSpawnFlags)(flags | G_SPAWN_LEAVE_DESCRIPTORS_OPEN); child_setup = close_non_standard_fds_linux; #endif gboolean spawned = g_spawn_async_with_pipes(NULL, argv, NULL, flags, child_setup, NULL, &pid, &stdin_fd, &stdout_fd, &stderr_fd, &error); if (!spawned) { ws_debug("Error creating async pipe: %s", error->message); g_free(error->message); } #endif g_free(command_line); g_strfreev(argv); ws_pipe->pid = pid; if (pid != WS_INVALID_PID) { #ifdef _WIN32 ws_pipe->stdin_io = g_io_channel_win32_new_fd(stdin_fd); ws_pipe->stdout_io = g_io_channel_win32_new_fd(stdout_fd); ws_pipe->stderr_io = g_io_channel_win32_new_fd(stderr_fd); #else ws_pipe->stdin_io = g_io_channel_unix_new(stdin_fd); ws_pipe->stdout_io = g_io_channel_unix_new(stdout_fd); ws_pipe->stderr_io = g_io_channel_unix_new(stderr_fd); #endif g_io_channel_set_encoding(ws_pipe->stdin_io, NULL, NULL); g_io_channel_set_encoding(ws_pipe->stdout_io, NULL, NULL); g_io_channel_set_encoding(ws_pipe->stderr_io, NULL, NULL); g_io_channel_set_buffered(ws_pipe->stdin_io, FALSE); g_io_channel_set_buffered(ws_pipe->stdout_io, FALSE); g_io_channel_set_buffered(ws_pipe->stderr_io, FALSE); g_io_channel_set_close_on_unref(ws_pipe->stdin_io, TRUE); g_io_channel_set_close_on_unref(ws_pipe->stdout_io, TRUE); g_io_channel_set_close_on_unref(ws_pipe->stderr_io, TRUE); } return pid; } #ifdef _WIN32 typedef struct { HANDLE pipeHandle; OVERLAPPED ol; BOOL pendingIO; } PIPEINTS; gboolean ws_pipe_wait_for_pipe(HANDLE * pipe_handles, int num_pipe_handles, HANDLE pid) { PIPEINTS pipeinsts[3]; HANDLE handles[4]; gboolean result = TRUE; SecureZeroMemory(pipeinsts, sizeof(pipeinsts)); if (num_pipe_handles == 0 || num_pipe_handles > 3) { ws_debug("Invalid number of pipes given as argument."); return FALSE; } for (int i = 0; i < num_pipe_handles; ++i) { pipeinsts[i].ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!pipeinsts[i].ol.hEvent) { ws_debug("Could not create overlapped event"); for (int j = 0; j < i; j++) { CloseHandle(pipeinsts[j].ol.hEvent); } return FALSE; } } for (int i = 0; i < num_pipe_handles; ++i) { pipeinsts[i].pipeHandle = pipe_handles[i]; pipeinsts[i].ol.Pointer = 0; pipeinsts[i].pendingIO = FALSE; if (!ConnectNamedPipe(pipeinsts[i].pipeHandle, &pipeinsts[i].ol)) { DWORD error = GetLastError(); switch (error) { case ERROR_IO_PENDING: pipeinsts[i].pendingIO = TRUE; break; case ERROR_PIPE_CONNECTED: SetEvent(pipeinsts[i].ol.hEvent); break; default: ws_debug("ConnectNamedPipe failed with %ld\n.", error); result = FALSE; } } } while (result) { DWORD dw; int num_handles = 0; for (int i = 0; i < num_pipe_handles; ++i) { if (pipeinsts[i].pendingIO) { handles[num_handles] = pipeinsts[i].ol.hEvent; num_handles++; } } if (num_handles == 0) { /* All pipes have been successfully connected */ break; } /* Wait for process in case it exits before the pipes have connected */ handles[num_handles] = pid; num_handles++; dw = WaitForMultipleObjects(num_handles, handles, FALSE, 30000); int handle_idx = dw - WAIT_OBJECT_0; if (dw == WAIT_TIMEOUT) { ws_debug("extcap didn't connect to pipe within 30 seconds."); result = FALSE; break; } // If index points to our handles array else if (handle_idx >= 0 && handle_idx < num_handles) { if (handles[handle_idx] == pid) { ws_debug("extcap terminated without connecting to pipe."); result = FALSE; } for (int i = 0; i < num_pipe_handles; ++i) { if (handles[handle_idx] == pipeinsts[i].ol.hEvent) { DWORD cbRet; BOOL success = GetOverlappedResult( pipeinsts[i].pipeHandle, // handle to pipe &pipeinsts[i].ol, // OVERLAPPED structure &cbRet, // bytes transferred TRUE); // wait if (!success) { ws_debug("Error %ld \n.", GetLastError()); result = FALSE; } pipeinsts[i].pendingIO = FALSE; } } } else { ws_debug("WaitForMultipleObjects returned 0x%08lX. Error %ld", dw, GetLastError()); result = FALSE; } } for (int i = 0; i < num_pipe_handles; ++i) { if (pipeinsts[i].pendingIO) { CancelIoEx(pipeinsts[i].pipeHandle, &pipeinsts[i].ol); WaitForSingleObject(pipeinsts[i].ol.hEvent, INFINITE); } CloseHandle(pipeinsts[i].ol.hEvent); } return result; } #endif gboolean ws_pipe_data_available(int pipe_fd) { #ifdef _WIN32 /* PeekNamedPipe */ HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd); DWORD bytes_avail; if (hPipe == INVALID_HANDLE_VALUE) { return FALSE; } if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL)) { return FALSE; } if (bytes_avail > 0) { return TRUE; } return FALSE; #else /* select */ fd_set rfds; struct timeval timeout; FD_ZERO(&rfds); FD_SET(pipe_fd, &rfds); timeout.tv_sec = 0; timeout.tv_usec = 0; if (select(pipe_fd + 1, &rfds, NULL, NULL, &timeout) > 0) { return TRUE; } return FALSE; #endif } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/ws_pipe.h
/** @file * * Routines for handling pipes. * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_PIPE_H__ #define __WS_PIPE_H__ // ws_symbol_export and WS_INVALID_PID #include "wsutil/processes.h" #include <glib.h> #ifdef _WIN32 #include <windows.h> #include <io.h> #define ws_pipe_handle HANDLE #define ws_get_pipe_handle(pipe_fd) ((HANDLE)_get_osfhandle(pipe_fd)) #else #define ws_pipe_handle int #define ws_get_pipe_handle(pipe_fd) (pipe_fd) #endif typedef struct _ws_pipe_t { GPid pid; GIOChannel *stdin_io; GIOChannel *stdout_io; GIOChannel *stderr_io; } ws_pipe_t; /** * @brief Run a process using g_spawn_sync on UNIX and Linux, and * CreateProcess on Windows. Wait for it to finish. * @param [IN] working_directory Initial working directory. * @param [IN] command Command to run. * @param [IN] argc Number of arguments for the command, not including the command itself. * @param [IN] args Arguments for the command, not including the command itself. * The last element must be NULL. * @param [OUT] command_output If not NULL, receives a copy of the command output. Must be g_freed. * @return TRUE on success or FALSE on failure. */ WS_DLL_PUBLIC gboolean ws_pipe_spawn_sync(const gchar * working_directory, const gchar * command, gint argc, gchar ** args, gchar ** command_output); /** * @brief Initialize a ws_pipe_t struct. Sets .pid to WS_INVALID_PID and all other members to 0 or NULL. * @param ws_pipe [IN] The pipe to initialize. */ WS_DLL_PUBLIC void ws_pipe_init(ws_pipe_t *ws_pipe); /** * @brief Checks whether a pipe is valid (for reading or writing). */ static inline gboolean ws_pipe_valid(ws_pipe_t *ws_pipe) { return ws_pipe && ws_pipe->pid && ws_pipe->pid != WS_INVALID_PID; } /** * @brief Start a process using g_spawn_sync on UNIX and Linux, and CreateProcess on Windows. * @param ws_pipe The process PID, stdio descriptors, etc. * @param args The command to run along with its arguments. * @return A valid PID on success, otherwise WS_INVALID_PID. */ WS_DLL_PUBLIC GPid ws_pipe_spawn_async (ws_pipe_t * ws_pipe, GPtrArray * args ); #ifdef _WIN32 /** * @brief Wait for a set of handles using WaitForMultipleObjects. Windows only. * @param pipe_handles An array of handles * @param num_pipe_handles The size of the array. * @param pid Child process PID. * @return TRUE on success or FALSE on failure. */ WS_DLL_PUBLIC gboolean ws_pipe_wait_for_pipe(HANDLE * pipe_handles, int num_pipe_handles, HANDLE pid); #endif /** * @brief Check to see if a file descriptor has data available. * @param pipe_fd File descriptor. * @return TRUE if data is available or FALSE otherwise. */ WS_DLL_PUBLIC gboolean ws_pipe_data_available(int pipe_fd); #endif /* __WS_PIPE_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/ws_return.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_RETURN_H__ #define __WS_RETURN_H__ #include <wsutil/wslog.h> #include <wsutil/wmem/wmem.h> /* * These macros can be used as an alternative to ws_assert() to * assert some condition on function arguments. This must only be used * to catch programming errors, in situations where an assertion is * appropriate. And it should only be used if failing the condition * doesn't necessarily lead to an inconsistent state for the program. * * It is possible to set the fatal log domain to "InvalidArg" to abort * execution for debugging purposes, if one of these checks fail. */ #define ws_warn_badarg(...) \ ws_log_full(LOG_DOMAIN_EINVAL, LOG_LEVEL_INFO, __FILE__, __LINE__, __func__, __VA_ARGS__) #define ws_warn_zero_len(var) ws_warn_badarg("Zero length argument '%s' is invalid", var) #define ws_warn_null_ptr(var) ws_warn_badarg("Null pointer argument '%s' is invalid", var) #define ws_return_str_if_zero(scope, len) \ do { \ if (!(len)) { \ ws_warn_zero_len(#len); \ return wmem_strdup(scope, "(zero length)"); \ } \ } while (0) #define ws_return_str_if_null(scope, ptr) \ do { \ if (!(ptr)) { \ ws_warn_null_ptr(#ptr); \ return wmem_strdup(scope, "(null pointer)"); \ } \ } while (0) #define ws_return_val_if_zero(len, val) \ do { \ if (!(len)) { \ ws_warn_zero_len(#len); \ return (val); \ } \ } while (0) #define ws_return_val_if_null(ptr, val) \ do { \ if (!(ptr)) { \ ws_warn_null_ptr(#ptr); \ return (val); \ } \ } while (0) #endif /* WS_RETURN_H_ */
C/C++
wireshark/wsutil/ws_roundup.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WS_ROUNDUP_H__ #define __WS_ROUNDUP_H__ /* * Round up to various powers of 2. */ #define WS_ROUNDUP_2(n) (((n) + ((guint)(2U-1U))) & (~((guint)(2U-1U)))) #define WS_ROUNDUP_4(n) (((n) + ((guint)(4U-1U))) & (~((guint)(4U-1U)))) #define WS_ROUNDUP_8(n) (((n) + ((guint)(8U-1U))) & (~((guint)(8U-1U)))) #define WS_ROUNDUP_16(n) (((n) + ((guint)(16U-1U))) & (~((guint)(16U-1U)))) #define WS_ROUNDUP_32(n) (((n) + ((guint)(32U-1U))) & (~((guint)(32U-1U)))) #endif /* __WS_ROUNDUP_H__ */
C
wireshark/wsutil/xtea.c
/* xtea.c * Implementation of XTEA cipher * By Ahmad Fatoum <ahmad[AT]a3f.at> * Copyright 2017 Ahmad Fatoum * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "xtea.h" #include <string.h> #include "pint.h" void decrypt_xtea_ecb(guint8 plaintext[8], const guint8 ciphertext[8], const guint32 key[4], guint num_rounds) { guint i; guint32 v[2], delta = 0x9E3779B9, sum = delta * num_rounds; v[0] = pntoh32(&ciphertext[0]); v[1] = pntoh32(&ciphertext[4]); for (i = 0; i < num_rounds; i++) { v[1] -= (((v[0] << 4) ^ (v[0] >> 5)) + v[0]) ^ (sum + key[(sum >> 11) & 3]); sum -= delta; v[0] -= (((v[1] << 4) ^ (v[1] >> 5)) + v[1]) ^ (sum + key[sum & 3]); } v[0] = GUINT32_TO_BE(v[0]); v[1] = GUINT32_TO_BE(v[1]); memcpy(plaintext, v, sizeof v); } void decrypt_xtea_le_ecb(guint8 plaintext[8], const guint8 ciphertext[8], const guint32 key[4], guint num_rounds) { guint i; guint32 v[2], delta = 0x9E3779B9, sum = delta * num_rounds; v[0] = pletoh32(&ciphertext[0]); v[1] = pletoh32(&ciphertext[4]); for (i = 0; i < num_rounds; i++) { v[1] -= (((v[0] << 4) ^ (v[0] >> 5)) + v[0]) ^ (sum + key[(sum >> 11) & 3]); sum -= delta; v[0] -= (((v[1] << 4) ^ (v[1] >> 5)) + v[1]) ^ (sum + key[sum & 3]); } v[0] = GUINT32_TO_LE(v[0]); v[1] = GUINT32_TO_LE(v[1]); memcpy(plaintext, v, sizeof v); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/xtea.h
/** @file * * Implementation of XTEA cipher * By Ahmad Fatoum <ahmad[AT]a3f.at> * Copyright 2017 Ahmad Fatoum * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __XTEA_H__ #define __XTEA_H__ /* Actual XTEA is big-endian, nevertheless there exist protocols that treat every block * as little endian, so we provide both */ #include "wireshark.h" WS_DLL_PUBLIC void decrypt_xtea_ecb(guint8 plaintext[8], const guint8 ciphertext[8], const guint32 key[4], guint num_rounds); WS_DLL_PUBLIC void decrypt_xtea_le_ecb(guint8 plaintext[8], const guint8 ciphertext[8], const guint32 key[4], guint num_rounds); #endif /* __XTEA_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/wmem/wmem-int.h
/** @file * * Internal definitions for the Wireshark Memory Manager * Copyright 2012, Evan Huus <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WMEM_INT_H__ #define __WMEM_INT_H__ #include <glib.h> #include <wsutil/ws_assert.h> #endif /* __WMEM_INT_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/wmem/wmem.h
/** @file * * Definitions for the Wireshark Memory Manager * Copyright 2012, Evan Huus <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WMEM_H__ #define __WMEM_H__ #include "wmem_array.h" #include "wmem_core.h" #include "wmem_list.h" #include "wmem_map.h" #include "wmem_miscutl.h" #include "wmem_multimap.h" #include "wmem_queue.h" #include "wmem_stack.h" #include "wmem_strbuf.h" #include "wmem_strutl.h" #include "wmem_tree.h" #include "wmem_interval_tree.h" #include "wmem_user_cb.h" #endif /* __WMEM_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/wmem/wmem_allocator.h
/** @file * * Definitions for the Wireshark Memory Manager Allocator * Copyright 2012, Evan Huus <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WMEM_ALLOCATOR_H__ #define __WMEM_ALLOCATOR_H__ #include <glib.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ struct _wmem_user_cb_container_t; /* See section "4. Internal Design" of doc/README.wmem for details * on this structure */ struct _wmem_allocator_t { /* Consumer functions */ void *(*walloc)(void *private_data, const size_t size); void (*wfree)(void *private_data, void *ptr); void *(*wrealloc)(void *private_data, void *ptr, const size_t size); /* Producer/Manager functions */ void (*free_all)(void *private_data); void (*gc)(void *private_data); void (*cleanup)(void *private_data); /* Callback List */ struct _wmem_user_cb_container_t *callbacks; /* Implementation details */ void *private_data; enum _wmem_allocator_type_t type; bool in_scope; }; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __WMEM_ALLOCATOR_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C
wireshark/wsutil/wmem/wmem_allocator_block.c
/* wmem_allocator_block.c * Wireshark Memory Manager Large-Block Allocator (version 3) * Copyright 2013, Evan Huus <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <stdio.h> #include <string.h> #include <glib.h> #include "wmem_core.h" #include "wmem_allocator.h" #include "wmem_allocator_block.h" /* This has turned into a very interesting excercise in algorithms and data * structures. * * HISTORY * * Version 1 of this allocator was embedded in the original emem framework. It * didn't have to handle realloc or free, so it was very simple: it just grabbed * a block from the OS and served allocations sequentially out of that until it * ran out, then allocated a new block. The old block was never revisited, so * it generally had a bit of wasted space at the end, but the waste was * small enough that it was simply ignored. This allocator provided very fast * constant-time allocation for any request that didn't require a new block from * the OS, and that cost could be amortized away. * * Version 2 of this allocator was prompted by the need to support realloc and * free in wmem. The original version simply didn't save enough metadata to do * this, so I added a layer on top to make it possible. The primary principle * was the same (allocate sequentially out of big blocks) with a bit of extra * magic. Allocations were still fast constant-time, and frees were as well. * Large parts of that design are still present in this one, but for more * details see older versions of this file from git or svn. * * Version 3 of this allocator was written to address some issues that * eventually showed up with version 2 under real-world usage. Specifically, * version 2 dealt very poorly with memory fragmentation, almost never reusing * freed blocks and choosing to just keep allocating from the master block * instead. This led to particularly poor behaviour under the tick-tock loads * (alloc/free/alloc/free or alloc/alloc/free/alloc/alloc/free/ or ...) that * showed up in a couple of different protocol dissectors (TCP, Kafka). * * BLOCKS AND CHUNKS * * As in previous versions, allocations typically happen sequentially out of * large OS-level blocks. Each block has a short embedded header used to * maintain a doubly-linked list of all blocks (used or not) currently owned by * the allocator. Each block is divided into chunks, which represent allocations * and free sections (a block is initialized with one large, free, chunk). Each * chunk is prefixed with a wmem_block_chunk_t structure, which is a short * metadata header (8 bytes, regardless of 32 or 64-bit architecture unless * alignment requires it to be padded) that contains the length of the chunk, * the length of the previous chunk, a flag marking the chunk as free or used, * and a flag marking the last chunk in a block. This serves to implement an * inline sequential doubly-linked list of all the chunks in each block. A block * with three chunks might look something like this: * * 0 _________________________ * ^ ___________ / ______________ \ __________ * ||---||--|-----/-----------||--------/--------------||--\-----/----------|| * ||hdr|| prv | len | body || prv | len | body || prv | len | body || * ||---||--------------------||--/--------------------||-------------------|| * \______________________/ * * * When allocating, a free chunk is found (more on that later) and split into * two chunks: the first of the requested size and the second containing any * remaining free. The first is marked used and returned to the caller. * * When freeing, the chunk in question is marked as free. Its neighbouring * chunks are then checked; if either of them are free, the consecutive free * chunks are merged into a single larger free chunk. Induction can show that * applying this operation consistently prevents us ever having consecutive * free chunks. * * Free chunks (because they are not being used for anything else) each store an * additional pair of pointers (see the wmem_block_free_t structure) that form * the backbone of the data structures used to track free chunks. * * MASTER AND RECYCLER * * The extra pair of pointers in free chunks are used to build two doubly-linked * lists: the master and the recycler. The recycler is circular, the master is * a stack. * * The master stack is only populated by chunks from new OS-level blocks, * so every chunk in this list is guaranteed to be able to serve any allocation * request (the allocator will not serve requests larger than its block size). * The chunk at the head of the master list shrinks as it serves requests. When * it is too small to serve the current request, it is popped and inserted into * the recycler. If the master list is empty, a new OS-level block is allocated, * and its chunk is pushed onto the master stack. * * The recycler is populated by 'leftovers' from the master, as well as any * chunks that were returned to the allocator via a call to free(). Although the * recycler is circular, we will refer to the element referenced from the * allocator as the 'head' of the list for convenience. The primary operation on * the recycler is called cycling it. In this operation, the head is compared * with its clockwise neighbour. If the neighbour is as large or larger, it * becomes the head (the list rotates counter-clockwise). If the neighbour is * smaller, then it is removed from its location and inserted as the counter- * clockwise neighbour of the head (the list still rotates counter-clockwise, * but the head element is held fixed while the rest of the list spins). This * operation has the following properties: * - fast constant time * - once the largest chunk is at the head, it remains at the head * - more iterations increases the probability that the largest chunk will be * the head (for a list with n items, n iterations guarantees that the * largest chunk will be the head). * * ALLOCATING * * When an allocation request is received, the allocator first attempts to * satisfy it with the chunk at the head of the recycler. If that does not * succeed, the request is satisfied by the master list instead. Regardless of * which chunk satisfied the request, the recycler is always cycled. */ /* https://mail.gnome.org/archives/gtk-devel-list/2004-December/msg00091.html * The 2*sizeof(size_t) alignment here is borrowed from GNU libc, so it should * be good most everywhere. It is more conservative than is needed on some * 64-bit platforms, but ia64 does require a 16-byte alignment. The SIMD * extensions for x86 and ppc32 would want a larger alignment than this, but * we don't need to do better than malloc. */ #define WMEM_ALIGN_AMOUNT (2 * sizeof (size_t)) #define WMEM_ALIGN_SIZE(SIZE) ((~(WMEM_ALIGN_AMOUNT-1)) & \ ((SIZE) + (WMEM_ALIGN_AMOUNT-1))) /* When required, allocate more memory from the OS in chunks of this size. * 8MB is a pretty arbitrary value - it's big enough that it should last a while * and small enough that a mostly-unused one doesn't waste *too* much. It's * also a nice power of two, of course. */ #define WMEM_BLOCK_SIZE (8 * 1024 * 1024) /* The header for an entire OS-level 'block' of memory */ typedef struct _wmem_block_hdr_t { struct _wmem_block_hdr_t *prev, *next; } wmem_block_hdr_t; /* The header for a single 'chunk' of memory as returned from alloc/realloc. * The 'jumbo' flag indicates an allocation larger than a normal-sized block * would be capable of serving. If this is set, it is the only chunk in the * block and the other chunk header fields are irrelevant. */ typedef struct _wmem_block_chunk_t { uint32_t prev; /* flags */ uint32_t last:1; uint32_t used:1; uint32_t jumbo:1; uint32_t len:29; } wmem_block_chunk_t; /* Handy macros for navigating the chunks in a block as if they were a * doubly-linked list. */ #define WMEM_CHUNK_PREV(CHUNK) ((CHUNK)->prev \ ? ((wmem_block_chunk_t*)(((uint8_t*)(CHUNK)) - (CHUNK)->prev)) \ : NULL) #define WMEM_CHUNK_NEXT(CHUNK) ((CHUNK)->last \ ? NULL \ : ((wmem_block_chunk_t*)(((uint8_t*)(CHUNK)) + (CHUNK)->len))) #define WMEM_CHUNK_HEADER_SIZE WMEM_ALIGN_SIZE(sizeof(wmem_block_chunk_t)) #define WMEM_BLOCK_MAX_ALLOC_SIZE (WMEM_BLOCK_SIZE - \ (WMEM_BLOCK_HEADER_SIZE + WMEM_CHUNK_HEADER_SIZE)) /* other handy chunk macros */ #define WMEM_CHUNK_TO_DATA(CHUNK) ((void*)((uint8_t*)(CHUNK) + WMEM_CHUNK_HEADER_SIZE)) #define WMEM_DATA_TO_CHUNK(DATA) ((wmem_block_chunk_t*)((uint8_t*)(DATA) - WMEM_CHUNK_HEADER_SIZE)) #define WMEM_CHUNK_DATA_LEN(CHUNK) ((CHUNK)->len - WMEM_CHUNK_HEADER_SIZE) /* some handy block macros */ #define WMEM_BLOCK_HEADER_SIZE WMEM_ALIGN_SIZE(sizeof(wmem_block_hdr_t)) #define WMEM_BLOCK_TO_CHUNK(BLOCK) ((wmem_block_chunk_t*)((uint8_t*)(BLOCK) + WMEM_BLOCK_HEADER_SIZE)) #define WMEM_CHUNK_TO_BLOCK(CHUNK) ((wmem_block_hdr_t*)((uint8_t*)(CHUNK) - WMEM_BLOCK_HEADER_SIZE)) /* This is what the 'data' section of a chunk contains if it is free. */ typedef struct _wmem_block_free_t { wmem_block_chunk_t *prev, *next; } wmem_block_free_t; /* Handy macro for accessing the free-header of a chunk */ #define WMEM_GET_FREE(CHUNK) ((wmem_block_free_t*)WMEM_CHUNK_TO_DATA(CHUNK)) typedef struct _wmem_block_allocator_t { wmem_block_hdr_t *block_list; wmem_block_chunk_t *master_head; wmem_block_chunk_t *recycler_head; } wmem_block_allocator_t; /* DEBUG AND TEST */ static int wmem_block_verify_block(wmem_block_hdr_t *block) { int total_free_space = 0; uint32_t total_len; wmem_block_chunk_t *chunk; chunk = WMEM_BLOCK_TO_CHUNK(block); total_len = WMEM_BLOCK_HEADER_SIZE; if (chunk->jumbo) { /* We can tell nothing else about jumbo chunks except that they are * always used. */ return 0; } g_assert_true(chunk->prev == 0); do { total_len += chunk->len; g_assert_true(chunk->len >= WMEM_CHUNK_HEADER_SIZE); g_assert_true(!chunk->jumbo); if (WMEM_CHUNK_NEXT(chunk)) { g_assert_true(chunk->len == WMEM_CHUNK_NEXT(chunk)->prev); } if (!chunk->used && WMEM_CHUNK_DATA_LEN(chunk) >= sizeof(wmem_block_free_t)) { total_free_space += chunk->len; if (!chunk->last) { g_assert_true(WMEM_GET_FREE(chunk)->next); g_assert_true(WMEM_GET_FREE(chunk)->prev); } } chunk = WMEM_CHUNK_NEXT(chunk); } while (chunk); g_assert_true(total_len == WMEM_BLOCK_SIZE); return total_free_space; } static int wmem_block_verify_master_list(wmem_block_allocator_t *allocator) { wmem_block_chunk_t *cur; wmem_block_free_t *cur_free; int free_space = 0; cur = allocator->master_head; if (!cur) { return 0; } g_assert_true(WMEM_GET_FREE(cur)->prev == NULL); while (cur) { free_space += cur->len; cur_free = WMEM_GET_FREE(cur); g_assert_true(! cur->used); if (cur_free->next) { g_assert_true(WMEM_GET_FREE(cur_free->next)->prev == cur); } if (cur != allocator->master_head) { g_assert_true(cur->len == WMEM_BLOCK_SIZE); } cur = cur_free->next; } return free_space; } static int wmem_block_verify_recycler(wmem_block_allocator_t *allocator) { wmem_block_chunk_t *cur; wmem_block_free_t *cur_free; int free_space = 0; cur = allocator->recycler_head; if (!cur) { return 0; } do { free_space += cur->len; cur_free = WMEM_GET_FREE(cur); g_assert_true(! cur->used); g_assert_true(cur_free->prev); g_assert_true(cur_free->next); g_assert_true(WMEM_GET_FREE(cur_free->prev)->next == cur); g_assert_true(WMEM_GET_FREE(cur_free->next)->prev == cur); cur = cur_free->next; } while (cur != allocator->recycler_head); return free_space; } void wmem_block_verify(wmem_allocator_t *allocator) { wmem_block_hdr_t *cur; wmem_block_allocator_t *private_allocator; int master_free, recycler_free, chunk_free = 0; /* Normally it would be bad for an allocator helper function to depend * on receiving the right type of allocator, but this is for testing only * and is not part of any real API. */ g_assert_true(allocator->type == WMEM_ALLOCATOR_BLOCK); private_allocator = (wmem_block_allocator_t*) allocator->private_data; if (private_allocator->block_list == NULL) { g_assert_true(! private_allocator->master_head); g_assert_true(! private_allocator->recycler_head); return; } master_free = wmem_block_verify_master_list(private_allocator); recycler_free = wmem_block_verify_recycler(private_allocator); cur = private_allocator->block_list; g_assert_true(cur->prev == NULL); while (cur) { if (cur->next) { g_assert_true(cur->next->prev == cur); } chunk_free += wmem_block_verify_block(cur); cur = cur->next; } g_assert_true(chunk_free == master_free + recycler_free); } /* MASTER/RECYCLER HELPERS */ /* Cycles the recycler. See the design notes at the top of this file for more * details. */ static void wmem_block_cycle_recycler(wmem_block_allocator_t *allocator) { wmem_block_chunk_t *chunk; wmem_block_free_t *free_chunk; chunk = allocator->recycler_head; if (chunk == NULL) { return; } free_chunk = WMEM_GET_FREE(chunk); if (free_chunk->next->len < chunk->len) { /* Hold the current head fixed during rotation. */ WMEM_GET_FREE(free_chunk->next)->prev = free_chunk->prev; WMEM_GET_FREE(free_chunk->prev)->next = free_chunk->next; free_chunk->prev = free_chunk->next; free_chunk->next = WMEM_GET_FREE(free_chunk->next)->next; WMEM_GET_FREE(free_chunk->next)->prev = chunk; WMEM_GET_FREE(free_chunk->prev)->next = chunk; } else { /* Just rotate everything. */ allocator->recycler_head = free_chunk->next; } } /* Adds a chunk from the recycler. */ static void wmem_block_add_to_recycler(wmem_block_allocator_t *allocator, wmem_block_chunk_t *chunk) { wmem_block_free_t *free_chunk; if (WMEM_CHUNK_DATA_LEN(chunk) < sizeof(wmem_block_free_t)) { return; } free_chunk = WMEM_GET_FREE(chunk); if (! allocator->recycler_head) { /* First one */ free_chunk->next = chunk; free_chunk->prev = chunk; allocator->recycler_head = chunk; } else { free_chunk->next = allocator->recycler_head; free_chunk->prev = WMEM_GET_FREE(allocator->recycler_head)->prev; WMEM_GET_FREE(free_chunk->next)->prev = chunk; WMEM_GET_FREE(free_chunk->prev)->next = chunk; if (chunk->len > allocator->recycler_head->len) { allocator->recycler_head = chunk; } } } /* Removes a chunk from the recycler. */ static void wmem_block_remove_from_recycler(wmem_block_allocator_t *allocator, wmem_block_chunk_t *chunk) { wmem_block_free_t *free_chunk; free_chunk = WMEM_GET_FREE(chunk); if (free_chunk->prev == chunk && free_chunk->next == chunk) { /* Only one item in recycler, just empty it. */ allocator->recycler_head = NULL; } else { /* Two or more items, usual doubly-linked-list removal. It's circular * so we don't need to worry about null-checking anything, which is * nice. */ WMEM_GET_FREE(free_chunk->prev)->next = free_chunk->next; WMEM_GET_FREE(free_chunk->next)->prev = free_chunk->prev; if (allocator->recycler_head == chunk) { allocator->recycler_head = free_chunk->next; } } } /* Pushes a chunk onto the master stack. */ static void wmem_block_push_master(wmem_block_allocator_t *allocator, wmem_block_chunk_t *chunk) { wmem_block_free_t *free_chunk; free_chunk = WMEM_GET_FREE(chunk); free_chunk->prev = NULL; free_chunk->next = allocator->master_head; if (free_chunk->next) { WMEM_GET_FREE(free_chunk->next)->prev = chunk; } allocator->master_head = chunk; } /* Removes the top chunk from the master stack. */ static void wmem_block_pop_master(wmem_block_allocator_t *allocator) { wmem_block_chunk_t *chunk; wmem_block_free_t *free_chunk; chunk = allocator->master_head; free_chunk = WMEM_GET_FREE(chunk); allocator->master_head = free_chunk->next; if (free_chunk->next) { WMEM_GET_FREE(free_chunk->next)->prev = NULL; } } /* CHUNK HELPERS */ /* Takes a free chunk and checks the chunks to its immediate right and left in * the block. If they are also free, the contigous free chunks are merged into * a single free chunk. The resulting chunk ends up in either the master list or * the recycler, depending on where the merged chunks were originally. */ static void wmem_block_merge_free(wmem_block_allocator_t *allocator, wmem_block_chunk_t *chunk) { wmem_block_chunk_t *tmp; wmem_block_chunk_t *left_free = NULL; wmem_block_chunk_t *right_free = NULL; /* Check the chunk to our right. If it is free, merge it into our current * chunk. If it is big enough to hold a free-header, save it for later (we * need to know about the left chunk before we decide what goes where). */ tmp = WMEM_CHUNK_NEXT(chunk); if (tmp && !tmp->used) { if (WMEM_CHUNK_DATA_LEN(tmp) >= sizeof(wmem_block_free_t)) { right_free = tmp; } chunk->len += tmp->len; chunk->last = tmp->last; } /* Check the chunk to our left. If it is free, merge our current chunk into * it (thus chunk = tmp). As before, save it if it has enough space to * hold a free-header. */ tmp = WMEM_CHUNK_PREV(chunk); if (tmp && !tmp->used) { if (WMEM_CHUNK_DATA_LEN(tmp) >= sizeof(wmem_block_free_t)) { left_free = tmp; } tmp->len += chunk->len; tmp->last = chunk->last; chunk = tmp; } /* The length of our chunk may have changed. If we have a chunk following, * update its 'prev' count. */ if (!chunk->last) { WMEM_CHUNK_NEXT(chunk)->prev = chunk->len; } /* Now that the chunk headers are merged and consistent, we need to figure * out what goes where in which free list. */ if (right_free && right_free == allocator->master_head) { /* If we merged right, and that chunk was the head of the master list, * then we leave the resulting chunk at the head of the master list. */ wmem_block_free_t *moved; if (left_free) { wmem_block_remove_from_recycler(allocator, left_free); } moved = WMEM_GET_FREE(chunk); moved->prev = NULL; moved->next = WMEM_GET_FREE(right_free)->next; allocator->master_head = chunk; if (moved->next) { WMEM_GET_FREE(moved->next)->prev = chunk; } } else { /* Otherwise, we remove the right-merged chunk (if there was one) from * the recycler. Then, if we merged left we have nothing to do, since * that recycler entry is still valid. If not, we add the chunk. */ if (right_free) { wmem_block_remove_from_recycler(allocator, right_free); } if (!left_free) { wmem_block_add_to_recycler(allocator, chunk); } } } /* Takes an unused chunk and a size, and splits it into two chunks if possible. * The first chunk (at the same address as the input chunk) is guaranteed to * hold at least `size` bytes of data, and to not be in either the master or * recycler lists. * * The second chunk gets whatever data is left over. It is marked unused and * replaces the input chunk in whichever list it originally inhabited. */ static void wmem_block_split_free_chunk(wmem_block_allocator_t *allocator, wmem_block_chunk_t *chunk, const size_t size) { wmem_block_chunk_t *extra; wmem_block_free_t *old_blk, *new_blk; size_t aligned_size, available; bool last; aligned_size = WMEM_ALIGN_SIZE(size) + WMEM_CHUNK_HEADER_SIZE; if (WMEM_CHUNK_DATA_LEN(chunk) < aligned_size + sizeof(wmem_block_free_t)) { /* If the available space is not enought to store all of * (hdr + requested size + alignment padding + hdr + free-header) then * just remove the current chunk from the free list and return, since we * can't usefully split it. */ if (chunk == allocator->master_head) { wmem_block_pop_master(allocator); } else if (WMEM_CHUNK_DATA_LEN(chunk) >= sizeof(wmem_block_free_t)) { wmem_block_remove_from_recycler(allocator, chunk); } return; } /* preserve a few values from chunk that we'll need to manipulate */ last = chunk->last; available = chunk->len - aligned_size; /* set new values for chunk */ chunk->len = (uint32_t) aligned_size; chunk->last = false; /* with chunk's values set, we can use the standard macro to calculate * the location and size of the new free chunk */ extra = WMEM_CHUNK_NEXT(chunk); /* Now we move the free chunk's address without changing its location * in whichever list it is in. * * Note that the new chunk header 'extra' may overlap the old free header, * so we have to copy the free header before we write anything to extra. */ old_blk = WMEM_GET_FREE(chunk); new_blk = WMEM_GET_FREE(extra); if (allocator->master_head == chunk) { new_blk->prev = old_blk->prev; new_blk->next = old_blk->next; if (old_blk->next) { WMEM_GET_FREE(old_blk->next)->prev = extra; } allocator->master_head = extra; } else { if (old_blk->prev == chunk) { new_blk->prev = extra; new_blk->next = extra; } else { new_blk->prev = old_blk->prev; new_blk->next = old_blk->next; WMEM_GET_FREE(old_blk->prev)->next = extra; WMEM_GET_FREE(old_blk->next)->prev = extra; } if (allocator->recycler_head == chunk) { allocator->recycler_head = extra; } } /* Now that we've copied over the free-list stuff (which may have overlapped * with our new chunk header) we can safely write our new chunk header. */ extra->len = (uint32_t) available; extra->last = last; extra->prev = chunk->len; extra->used = false; extra->jumbo = false; /* Correctly update the following chunk's back-pointer */ if (!last) { WMEM_CHUNK_NEXT(extra)->prev = extra->len; } } /* Takes a used chunk and a size, and splits it into two chunks if possible. * The first chunk can hold at least `size` bytes of data, while the second gets * whatever's left over. The second is marked as unused and is added to the * recycler. */ static void wmem_block_split_used_chunk(wmem_block_allocator_t *allocator, wmem_block_chunk_t *chunk, const size_t size) { wmem_block_chunk_t *extra; size_t aligned_size, available; bool last; aligned_size = WMEM_ALIGN_SIZE(size) + WMEM_CHUNK_HEADER_SIZE; if (aligned_size > WMEM_CHUNK_DATA_LEN(chunk)) { /* in this case we don't have enough space to really split it, so * it's basically a no-op */ return; } /* otherwise, we have room to split it, though the remaining free chunk * may still not be usefully large */ /* preserve a few values from chunk that we'll need to manipulate */ last = chunk->last; available = chunk->len - aligned_size; /* set new values for chunk */ chunk->len = (uint32_t) aligned_size; chunk->last = false; /* with chunk's values set, we can use the standard macro to calculate * the location and size of the new free chunk */ extra = WMEM_CHUNK_NEXT(chunk); /* set the new values for the chunk */ extra->len = (uint32_t) available; extra->last = last; extra->prev = chunk->len; extra->used = false; extra->jumbo = false; /* Correctly update the following chunk's back-pointer */ if (!last) { WMEM_CHUNK_NEXT(extra)->prev = extra->len; } /* Merge it to its right if possible (it can't be merged left, obviously). * This also adds it to the recycler. */ wmem_block_merge_free(allocator, extra); } /* BLOCK HELPERS */ /* Add a block to the allocator's embedded doubly-linked list of OS-level blocks * that it owns. */ static void wmem_block_add_to_block_list(wmem_block_allocator_t *allocator, wmem_block_hdr_t *block) { block->prev = NULL; block->next = allocator->block_list; if (block->next) { block->next->prev = block; } allocator->block_list = block; } /* Remove a block from the allocator's embedded doubly-linked list of OS-level * blocks that it owns. */ static void wmem_block_remove_from_block_list(wmem_block_allocator_t *allocator, wmem_block_hdr_t *block) { if (block->prev) { block->prev->next = block->next; } else { allocator->block_list = block->next; } if (block->next) { block->next->prev = block->prev; } } /* Initializes a single unused chunk at the beginning of the block, and * adds that chunk to the free list. */ static void wmem_block_init_block(wmem_block_allocator_t *allocator, wmem_block_hdr_t *block) { wmem_block_chunk_t *chunk; /* a new block contains one chunk, right at the beginning */ chunk = WMEM_BLOCK_TO_CHUNK(block); chunk->used = false; chunk->jumbo = false; chunk->last = true; chunk->prev = 0; chunk->len = WMEM_BLOCK_SIZE - WMEM_BLOCK_HEADER_SIZE; /* now push that chunk onto the master list */ wmem_block_push_master(allocator, chunk); } /* Creates a new block, and initializes it. */ static void wmem_block_new_block(wmem_block_allocator_t *allocator) { wmem_block_hdr_t *block; /* allocate the new block and add it to the block list */ block = (wmem_block_hdr_t *)wmem_alloc(NULL, WMEM_BLOCK_SIZE); wmem_block_add_to_block_list(allocator, block); /* initialize it */ wmem_block_init_block(allocator, block); } /* JUMBO ALLOCATIONS */ /* Allocates special 'jumbo' blocks for sizes that won't fit normally. */ static void * wmem_block_alloc_jumbo(wmem_block_allocator_t *allocator, const size_t size) { wmem_block_hdr_t *block; wmem_block_chunk_t *chunk; /* allocate a new block of exactly the right size */ block = (wmem_block_hdr_t *) wmem_alloc(NULL, size + WMEM_BLOCK_HEADER_SIZE + WMEM_CHUNK_HEADER_SIZE); /* add it to the block list */ wmem_block_add_to_block_list(allocator, block); /* the new block contains a single jumbo chunk */ chunk = WMEM_BLOCK_TO_CHUNK(block); chunk->last = true; chunk->used = true; chunk->jumbo = true; chunk->len = 0; chunk->prev = 0; /* and return the data pointer */ return WMEM_CHUNK_TO_DATA(chunk); } /* Frees special 'jumbo' blocks of sizes that won't fit normally. */ static void wmem_block_free_jumbo(wmem_block_allocator_t *allocator, wmem_block_chunk_t *chunk) { wmem_block_hdr_t *block; block = WMEM_CHUNK_TO_BLOCK(chunk); wmem_block_remove_from_block_list(allocator, block); wmem_free(NULL, block); } /* Reallocs special 'jumbo' blocks of sizes that won't fit normally. */ static void * wmem_block_realloc_jumbo(wmem_block_allocator_t *allocator, wmem_block_chunk_t *chunk, const size_t size) { wmem_block_hdr_t *block; block = WMEM_CHUNK_TO_BLOCK(chunk); block = (wmem_block_hdr_t *) wmem_realloc(NULL, block, size + WMEM_BLOCK_HEADER_SIZE + WMEM_CHUNK_HEADER_SIZE); if (block->next) { block->next->prev = block; } if (block->prev) { block->prev->next = block; } else { allocator->block_list = block; } return WMEM_CHUNK_TO_DATA(WMEM_BLOCK_TO_CHUNK(block)); } /* API */ static void * wmem_block_alloc(void *private_data, const size_t size) { wmem_block_allocator_t *allocator = (wmem_block_allocator_t*) private_data; wmem_block_chunk_t *chunk; if (size > WMEM_BLOCK_MAX_ALLOC_SIZE) { return wmem_block_alloc_jumbo(allocator, size); } if (allocator->recycler_head && WMEM_CHUNK_DATA_LEN(allocator->recycler_head) >= size) { /* If we can serve it from the recycler, do so. */ chunk = allocator->recycler_head; } else { if (allocator->master_head && WMEM_CHUNK_DATA_LEN(allocator->master_head) < size) { /* Recycle the head of the master list if necessary. */ chunk = allocator->master_head; wmem_block_pop_master(allocator); wmem_block_add_to_recycler(allocator, chunk); } if (!allocator->master_head) { /* Allocate a new block if necessary. */ wmem_block_new_block(allocator); } chunk = allocator->master_head; } /* Split our chunk into two to preserve any trailing free space */ wmem_block_split_free_chunk(allocator, chunk, size); /* Now cycle the recycler */ wmem_block_cycle_recycler(allocator); /* mark it as used */ chunk->used = true; /* and return the user's pointer */ return WMEM_CHUNK_TO_DATA(chunk); } static void wmem_block_free(void *private_data, void *ptr) { wmem_block_allocator_t *allocator = (wmem_block_allocator_t*) private_data; wmem_block_chunk_t *chunk; chunk = WMEM_DATA_TO_CHUNK(ptr); if (chunk->jumbo) { wmem_block_free_jumbo(allocator, chunk); return; } /* mark it as unused */ chunk->used = false; /* merge it with any other free chunks adjacent to it, so that contiguous * free space doesn't get fragmented */ wmem_block_merge_free(allocator, chunk); /* Now cycle the recycler */ wmem_block_cycle_recycler(allocator); } static void * wmem_block_realloc(void *private_data, void *ptr, const size_t size) { wmem_block_allocator_t *allocator = (wmem_block_allocator_t*) private_data; wmem_block_chunk_t *chunk; chunk = WMEM_DATA_TO_CHUNK(ptr); if (chunk->jumbo) { return wmem_block_realloc_jumbo(allocator, chunk, size); } if (size > WMEM_CHUNK_DATA_LEN(chunk)) { /* grow */ wmem_block_chunk_t *tmp; tmp = WMEM_CHUNK_NEXT(chunk); if (tmp && (!tmp->used) && (size < WMEM_CHUNK_DATA_LEN(chunk) + tmp->len)) { /* the next chunk is free and has enough extra, so just grab * from that */ size_t split_size; /* we ask for the next chunk to be split, but we don't end up * using the split chunk header (it just gets merged into this one), * so we want the split to be of (size - curdatalen - header_size). * However, this can underflow by header_size, so we do a quick * check here and floor the value to 0. */ split_size = size - WMEM_CHUNK_DATA_LEN(chunk); if (split_size < WMEM_CHUNK_HEADER_SIZE) { split_size = 0; } else { split_size -= WMEM_CHUNK_HEADER_SIZE; } wmem_block_split_free_chunk(allocator, tmp, split_size); /* Now do a 'quickie' merge between the current block and the left- * hand side of the split. Simply calling wmem_block_merge_free * might confuse things, since we may temporarily have two blocks * to our right that are both free (and it isn't guaranteed to * handle that case). Update our 'next' count and last flag, and * our (new) successor's 'prev' count */ chunk->len += tmp->len; chunk->last = tmp->last; tmp = WMEM_CHUNK_NEXT(chunk); if (tmp) { tmp->prev = chunk->len; } /* Now cycle the recycler */ wmem_block_cycle_recycler(allocator); /* And return the same old pointer */ return ptr; } else { /* no room to grow, need to alloc, copy, free */ void *newptr; newptr = wmem_block_alloc(private_data, size); memcpy(newptr, ptr, WMEM_CHUNK_DATA_LEN(chunk)); wmem_block_free(private_data, ptr); /* No need to cycle the recycler, alloc and free both did that * already */ return newptr; } } else if (size < WMEM_CHUNK_DATA_LEN(chunk)) { /* shrink */ wmem_block_split_used_chunk(allocator, chunk, size); /* Now cycle the recycler */ wmem_block_cycle_recycler(allocator); return ptr; } /* no-op */ return ptr; } static void wmem_block_free_all(void *private_data) { wmem_block_allocator_t *allocator = (wmem_block_allocator_t*) private_data; wmem_block_hdr_t *cur; wmem_block_chunk_t *chunk; /* the existing free lists are entirely irrelevant */ allocator->master_head = NULL; allocator->recycler_head = NULL; /* iterate through the blocks, reinitializing each one */ cur = allocator->block_list; while (cur) { chunk = WMEM_BLOCK_TO_CHUNK(cur); if (chunk->jumbo) { wmem_block_remove_from_block_list(allocator, cur); cur = cur->next; wmem_free(NULL, WMEM_CHUNK_TO_BLOCK(chunk)); } else { wmem_block_init_block(allocator, cur); cur = cur->next; } } } static void wmem_block_gc(void *private_data) { wmem_block_allocator_t *allocator = (wmem_block_allocator_t*) private_data; wmem_block_hdr_t *cur, *next; wmem_block_chunk_t *chunk; wmem_block_free_t *free_chunk; /* Walk through the blocks, adding used blocks to the new list and * completely destroying unused blocks. */ cur = allocator->block_list; allocator->block_list = NULL; while (cur) { chunk = WMEM_BLOCK_TO_CHUNK(cur); next = cur->next; if (!chunk->jumbo && !chunk->used && chunk->last) { /* If the first chunk is also the last, and is unused, then * the block as a whole is entirely unused, so return it to * the OS and remove it from whatever lists it is in. */ free_chunk = WMEM_GET_FREE(chunk); if (free_chunk->next) { WMEM_GET_FREE(free_chunk->next)->prev = free_chunk->prev; } if (free_chunk->prev) { WMEM_GET_FREE(free_chunk->prev)->next = free_chunk->next; } if (allocator->recycler_head == chunk) { if (free_chunk->next == chunk) { allocator->recycler_head = NULL; } else { allocator->recycler_head = free_chunk->next; } } else if (allocator->master_head == chunk) { allocator->master_head = free_chunk->next; } wmem_free(NULL, cur); } else { /* part of this block is used, so add it to the new block list */ wmem_block_add_to_block_list(allocator, cur); } cur = next; } } static void wmem_block_allocator_cleanup(void *private_data) { /* wmem guarantees that free_all() is called directly before this, so * calling gc will return all our blocks to the OS automatically */ wmem_block_gc(private_data); /* then just free the allocator structs */ wmem_free(NULL, private_data); } void wmem_block_allocator_init(wmem_allocator_t *allocator) { wmem_block_allocator_t *block_allocator; block_allocator = wmem_new(NULL, wmem_block_allocator_t); allocator->walloc = &wmem_block_alloc; allocator->wrealloc = &wmem_block_realloc; allocator->wfree = &wmem_block_free; allocator->free_all = &wmem_block_free_all; allocator->gc = &wmem_block_gc; allocator->cleanup = &wmem_block_allocator_cleanup; allocator->private_data = (void*) block_allocator; block_allocator->block_list = NULL; block_allocator->master_head = NULL; block_allocator->recycler_head = NULL; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/wmem/wmem_allocator_block.h
/** @file * * Definitions for the Wireshark Memory Manager Large-Block Allocator * Copyright 2012, Evan Huus <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WMEM_ALLOCATOR_BLOCK_H__ #define __WMEM_ALLOCATOR_BLOCK_H__ #include "wmem_core.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ void wmem_block_allocator_init(wmem_allocator_t *allocator); /* Exposed only for testing purposes */ void wmem_block_verify(wmem_allocator_t *allocator); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __WMEM_ALLOCATOR_BLOCK_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C
wireshark/wsutil/wmem/wmem_allocator_block_fast.c
/* wmem_allocator_block.c * Wireshark Memory Manager Fast Large-Block Allocator * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <stdio.h> #include <string.h> #include <glib.h> #include "wmem_core.h" #include "wmem_allocator.h" #include "wmem_allocator_block_fast.h" /* https://mail.gnome.org/archives/gtk-devel-list/2004-December/msg00091.html * The 2*sizeof(size_t) alignment here is borrowed from GNU libc, so it should * be good most everywhere. It is more conservative than is needed on some * 64-bit platforms, but ia64 does require a 16-byte alignment. The SIMD * extensions for x86 and ppc32 would want a larger alignment than this, but * we don't need to do better than malloc. */ #define WMEM_ALIGN_AMOUNT (2 * sizeof (size_t)) #define WMEM_ALIGN_SIZE(SIZE) ((~(WMEM_ALIGN_AMOUNT-1)) & \ ((SIZE) + (WMEM_ALIGN_AMOUNT-1))) #define WMEM_CHUNK_TO_DATA(CHUNK) ((void*)((uint8_t*)(CHUNK) + WMEM_CHUNK_HEADER_SIZE)) #define WMEM_DATA_TO_CHUNK(DATA) ((wmem_block_fast_chunk_t*)((uint8_t*)(DATA) - WMEM_CHUNK_HEADER_SIZE)) #define WMEM_BLOCK_MAX_ALLOC_SIZE (WMEM_BLOCK_SIZE - (WMEM_BLOCK_HEADER_SIZE + WMEM_CHUNK_HEADER_SIZE)) /* When required, allocate more memory from the OS in chunks of this size. * 2MB is a pretty arbitrary value - it's big enough that it should last a while * and small enough that a mostly-unused one doesn't waste *too* much. It's * also a nice power of two, of course. */ #define WMEM_BLOCK_SIZE (2 * 1024 * 1024) /* The header for an entire OS-level 'block' of memory */ typedef struct _wmem_block_fast_hdr { struct _wmem_block_fast_hdr *next; int32_t pos; } wmem_block_fast_hdr_t; #define WMEM_BLOCK_HEADER_SIZE WMEM_ALIGN_SIZE(sizeof(wmem_block_fast_hdr_t)) typedef struct { uint32_t len; } wmem_block_fast_chunk_t; #define WMEM_CHUNK_HEADER_SIZE WMEM_ALIGN_SIZE(sizeof(wmem_block_fast_chunk_t)) #define JUMBO_MAGIC 0xFFFFFFFF typedef struct _wmem_block_fast_jumbo { struct _wmem_block_fast_jumbo *prev, *next; } wmem_block_fast_jumbo_t; #define WMEM_JUMBO_HEADER_SIZE WMEM_ALIGN_SIZE(sizeof(wmem_block_fast_jumbo_t)) typedef struct { wmem_block_fast_hdr_t *block_list; wmem_block_fast_jumbo_t *jumbo_list; } wmem_block_fast_allocator_t; /* Creates a new block, and initializes it. */ static inline void wmem_block_fast_new_block(wmem_block_fast_allocator_t *allocator) { wmem_block_fast_hdr_t *block; /* allocate/initialize the new block and add it to the block list */ block = (wmem_block_fast_hdr_t *)wmem_alloc(NULL, WMEM_BLOCK_SIZE); block->pos = WMEM_BLOCK_HEADER_SIZE; block->next = allocator->block_list; allocator->block_list = block; } /* API */ static void * wmem_block_fast_alloc(void *private_data, const size_t size) { wmem_block_fast_allocator_t *allocator = (wmem_block_fast_allocator_t*) private_data; wmem_block_fast_chunk_t *chunk; int32_t real_size; if (size > WMEM_BLOCK_MAX_ALLOC_SIZE) { wmem_block_fast_jumbo_t *block; /* allocate/initialize a new block of the necessary size */ block = (wmem_block_fast_jumbo_t *)wmem_alloc(NULL, size + WMEM_JUMBO_HEADER_SIZE + WMEM_CHUNK_HEADER_SIZE); block->next = allocator->jumbo_list; if (block->next) { block->next->prev = block; } block->prev = NULL; allocator->jumbo_list = block; chunk = ((wmem_block_fast_chunk_t*)((uint8_t*)(block) + WMEM_JUMBO_HEADER_SIZE)); chunk->len = JUMBO_MAGIC; return WMEM_CHUNK_TO_DATA(chunk); } real_size = (int32_t)(WMEM_ALIGN_SIZE(size) + WMEM_CHUNK_HEADER_SIZE); /* Allocate a new block if necessary. */ if (!allocator->block_list || (WMEM_BLOCK_SIZE - allocator->block_list->pos) < real_size) { wmem_block_fast_new_block(allocator); } chunk = (wmem_block_fast_chunk_t *) ((uint8_t *) allocator->block_list + allocator->block_list->pos); /* safe to cast, size smaller than WMEM_BLOCK_MAX_ALLOC_SIZE */ chunk->len = (uint32_t) size; allocator->block_list->pos += real_size; /* and return the user's pointer */ return WMEM_CHUNK_TO_DATA(chunk); } static void wmem_block_fast_free(void *private_data _U_, void *ptr _U_) { /* free is NOP */ } static void * wmem_block_fast_realloc(void *private_data, void *ptr, const size_t size) { wmem_block_fast_chunk_t *chunk; chunk = WMEM_DATA_TO_CHUNK(ptr); if (chunk->len == JUMBO_MAGIC) { wmem_block_fast_jumbo_t *block; block = ((wmem_block_fast_jumbo_t*)((uint8_t*)(chunk) - WMEM_JUMBO_HEADER_SIZE)); block = (wmem_block_fast_jumbo_t*)wmem_realloc(NULL, block, size + WMEM_JUMBO_HEADER_SIZE + WMEM_CHUNK_HEADER_SIZE); if (block->prev) { block->prev->next = block; } else { wmem_block_fast_allocator_t *allocator = (wmem_block_fast_allocator_t*) private_data; allocator->jumbo_list = block; } if (block->next) { block->next->prev = block; } return ((void*)((uint8_t*)(block) + WMEM_JUMBO_HEADER_SIZE + WMEM_CHUNK_HEADER_SIZE)); } else if (chunk->len < size) { /* grow */ void *newptr; /* need to alloc and copy; free is no-op, so don't call it */ newptr = wmem_block_fast_alloc(private_data, size); memcpy(newptr, ptr, chunk->len); return newptr; } /* shrink or same space - great we can do nothing */ return ptr; } static void wmem_block_fast_free_all(void *private_data) { wmem_block_fast_allocator_t *allocator = (wmem_block_fast_allocator_t*) private_data; wmem_block_fast_hdr_t *cur, *nxt; wmem_block_fast_jumbo_t *cur_jum, *nxt_jum; /* iterate through the blocks, freeing all but the first and reinitializing * that one */ cur = allocator->block_list; if (cur) { cur->pos = WMEM_BLOCK_HEADER_SIZE; nxt = cur->next; cur->next = NULL; cur = nxt; } while (cur) { nxt = cur->next; wmem_free(NULL, cur); cur = nxt; } /* now do the jumbo blocks, freeing all of them */ cur_jum = allocator->jumbo_list; while (cur_jum) { nxt_jum = cur_jum->next; wmem_free(NULL, cur_jum); cur_jum = nxt_jum; } allocator->jumbo_list = NULL; } static void wmem_block_fast_gc(void *private_data _U_) { /* No-op */ } static void wmem_block_fast_allocator_cleanup(void *private_data) { wmem_block_fast_allocator_t *allocator = (wmem_block_fast_allocator_t*) private_data; /* wmem guarantees that free_all() is called directly before this, so * simply free the first block */ wmem_free(NULL, allocator->block_list); /* then just free the allocator structs */ wmem_free(NULL, private_data); } void wmem_block_fast_allocator_init(wmem_allocator_t *allocator) { wmem_block_fast_allocator_t *block_allocator; block_allocator = wmem_new(NULL, wmem_block_fast_allocator_t); allocator->walloc = &wmem_block_fast_alloc; allocator->wrealloc = &wmem_block_fast_realloc; allocator->wfree = &wmem_block_fast_free; allocator->free_all = &wmem_block_fast_free_all; allocator->gc = &wmem_block_fast_gc; allocator->cleanup = &wmem_block_fast_allocator_cleanup; allocator->private_data = (void*) block_allocator; block_allocator->block_list = NULL; block_allocator->jumbo_list = NULL; } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C/C++
wireshark/wsutil/wmem/wmem_allocator_block_fast.h
/** @file * * Definitions for the Wireshark Memory Manager Fast Large-Block Allocator * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef __WMEM_ALLOCATOR_BLOCK_FAST_H__ #define __WMEM_ALLOCATOR_BLOCK_FAST_H__ #include "wmem_core.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ void wmem_block_fast_allocator_init(wmem_allocator_t *allocator); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __WMEM_ALLOCATOR_BLOCK_FAST_H__ */ /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
C
wireshark/wsutil/wmem/wmem_allocator_simple.c
/* wmem_allocator_simple.c * Wireshark Memory Manager Simple Allocator * Copyright 2012, Evan Huus <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <string.h> #include <glib.h> #include "wmem_core.h" #include "wmem_allocator.h" #include "wmem_allocator_simple.h" #define DEFAULT_ALLOCS 8192 typedef struct _wmem_simple_allocator_t { int size; int count; void **ptrs; } wmem_simple_allocator_t; static void * wmem_simple_alloc(void *private_data, const size_t size) { wmem_simple_allocator_t *allocator; allocator = (wmem_simple_allocator_t*) private_data; if (G_UNLIKELY(allocator->count == allocator->size)) { allocator->size *= 2; allocator->ptrs = (void**)wmem_realloc(NULL, allocator->ptrs, sizeof(void*) * allocator->size); } return allocator->ptrs[allocator->count++] = wmem_alloc(NULL, size); } static void wmem_simple_free(void *private_data, void *ptr) { int i; wmem_simple_allocator_t *allocator; allocator = (wmem_simple_allocator_t*) private_data; wmem_free(NULL, ptr); allocator->count--; for (i=allocator->count; i>=0; i--) { if (ptr == allocator->ptrs[i]) { if (i < allocator->count) { allocator->ptrs[i] = allocator->ptrs[allocator->count]; } return; } } g_assert_not_reached(); } static void * wmem_simple_realloc(void *private_data, void *ptr, const size_t size) { int i; wmem_simple_allocator_t *allocator; allocator = (wmem_simple_allocator_t*) private_data; for (i=allocator->count-1; i>=0; i--) { if (ptr == allocator->ptrs[i]) { return allocator->ptrs[i] = wmem_realloc(NULL, allocator->ptrs[i], size); } } g_assert_not_reached(); /* not reached */ return NULL; } static void wmem_simple_free_all(void *private_data) { wmem_simple_allocator_t *allocator; int i; allocator = (wmem_simple_allocator_t*) private_data; for (i = 0; i<allocator->count; i++) { wmem_free(NULL, allocator->ptrs[i]); } allocator->count = 0; } static void wmem_simple_gc(void *private_data _U_) { /* In this simple allocator, there is nothing to garbage-collect */ } static void wmem_simple_allocator_cleanup(void *private_data) { wmem_simple_allocator_t *allocator; allocator = (wmem_simple_allocator_t*) private_data; wmem_free(NULL, allocator->ptrs); wmem_free(NULL, allocator); } void wmem_simple_allocator_init(wmem_allocator_t *allocator) { wmem_simple_allocator_t *simple_allocator; simple_allocator = wmem_new(NULL, wmem_simple_allocator_t); allocator->walloc = &wmem_simple_alloc; allocator->wrealloc = &wmem_simple_realloc; allocator->wfree = &wmem_simple_free; allocator->free_all = &wmem_simple_free_all; allocator->gc = &wmem_simple_gc; allocator->cleanup = &wmem_simple_allocator_cleanup; allocator->private_data = (void*) simple_allocator; simple_allocator->count = 0; simple_allocator->size = DEFAULT_ALLOCS; simple_allocator->ptrs = wmem_alloc_array(NULL, void*, DEFAULT_ALLOCS); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */